Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6c5c29c92 | ||
|
|
a663f70e24 | ||
|
|
10dc621cac | ||
|
|
bee6c0093e | ||
|
|
cd9685fdf7 | ||
|
|
0c017082ee | ||
|
|
0338189ffa | ||
|
|
a092e82f7f | ||
|
|
fede9ff793 | ||
|
|
2914859505 | ||
|
|
ce964edcd4 | ||
|
|
b140869281 | ||
|
|
4c4bad4be0 | ||
|
|
807758d924 | ||
|
|
0d29e1f382 | ||
|
|
c3aaec9798 | ||
|
|
28b92f4eda | ||
|
|
bbe4ecf705 | ||
|
|
40886aa815 | ||
|
|
1bd0da305d | ||
|
|
06e0eea782 | ||
|
|
79acbc377a | ||
|
|
fdd5401b06 | ||
|
|
d7d19ffb2d | ||
|
|
1b643c0bc2 | ||
|
|
0f183559e5 | ||
|
|
46d46c71a6 | ||
|
|
60d87dcf35 | ||
|
|
322821289e | ||
|
|
27d84c3c99 | ||
|
|
cb7298077d | ||
|
|
135066bad2 | ||
|
|
b27da3f095 | ||
|
|
459ddf542a | ||
|
|
e2d085a534 | ||
|
|
61d97ea429 | ||
|
|
1692b77a99 | ||
|
|
9511270b71 | ||
|
|
a98b10c816 | ||
|
|
c025a00415 |
No files matched your search
@@ -1,7 +0,0 @@
|
||||
mongoURI=mongodb://localhost:27017
|
||||
dbo=school
|
||||
secret=<your 256 bit secret>
|
||||
PORT=8000
|
||||
SYSTEM_EMAIL_ADDRESS=<@exampleschoolemail.com>
|
||||
SYSTEM_EMAIL=<your system email>
|
||||
SYSTEM_PASSWORD=<your system password>
|
||||
@@ -0,0 +1 @@
|
||||
github: SowinskiBraeden
|
||||
+3
-3
@@ -1,6 +1,9 @@
|
||||
# Environment
|
||||
.env
|
||||
|
||||
# Vendor
|
||||
/vendor/*
|
||||
|
||||
# Pycache
|
||||
/test/__pycache__/*
|
||||
/test/util/__pycache__/*
|
||||
@@ -11,6 +14,3 @@
|
||||
|
||||
# Test output
|
||||
/test/output/*
|
||||
|
||||
# Sample Data
|
||||
/test/sample_data/*
|
||||
@@ -1,13 +0,0 @@
|
||||
<!-- CONTRIBUTING -->
|
||||
## Contributing
|
||||
|
||||
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.
|
||||
|
||||
If you have a suggestion that would make this better, please create a pull request. You can also simply open an issue with the tag "enhancement".
|
||||
Don't forget to give the project a star! Thanks again!
|
||||
|
||||
1. Clone the Project
|
||||
2. Create your Feature Branch (`git checkout -b update/AmazingFeature`)
|
||||
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
|
||||
4. Push to the Branch (`git push origin update/AmazingFeature`)
|
||||
5. Open a Pull Request
|
||||
+479
-62
@@ -40,19 +40,26 @@ The School Management API Documentation, defining all functions and their purpos
|
||||
* [Photo](#update-teacher-photo)
|
||||
<br></br>
|
||||
* **Update Admin...**
|
||||
* [Name](#update-admin-name) - **(Coming Soon)**
|
||||
* [Password](#update-admin-password) - **(Coming Soon)**
|
||||
* [Email](#update-admin-email) - **(Coming Soon)**
|
||||
* [Photo](#update-admin-photo) - **(Coming Soon)**
|
||||
* [Managing Contacts](#managing-contacts) - **(Not Documented)**
|
||||
* [Create Contact](#create-contact) - **(Not Documented)**
|
||||
* [Update Contact Name](#update-contact-name) - **(Not Documented)**
|
||||
* [Update Contact Address](#update-contact-address) - **(Not Documented)**
|
||||
* [Update Contact Home Phone](#update-contact-home-phone) - **(Not Documented)**
|
||||
* [Update Contact Work Phone](#update-contact-work-phone) - **(Not Documented)**
|
||||
* [Update Contact Email](#update-contact-email) - **(Not Documented)**
|
||||
* [Update Contact Priority](#update-contact-priority) - **(Not Documented)**
|
||||
* [Delete Contact](#delete-contact) - **(Not Documented)**
|
||||
* [Name](#update-admin-name)
|
||||
* [Password](#update-admin-password)
|
||||
* [Email](#update-admin-email)
|
||||
* [Managing Contacts](#managing-contacts)
|
||||
* [Create Contact](#create-contact)
|
||||
* [Update Contact Name](#update-contact-name)
|
||||
* [Update Contact Address](#update-contact-address)
|
||||
* [Update Contact Home Phone](#update-contact-home-phone)
|
||||
* [Update Contact Work Phone](#update-contact-work-phone)
|
||||
* [Update Contact Email](#update-contact-email)
|
||||
* [Update Contact Priority](#update-contact-priority)
|
||||
* [Delete Contact](#delete-contact)
|
||||
* [Remove Users](#remove-users)
|
||||
* [Remove Admin](#remove-admin)
|
||||
* [Remove Teacher](#remove-teacher)
|
||||
* [Remove Student](#remove-student)
|
||||
* [Admin Commands](#admin-commands)
|
||||
* [Update Locker Combination](#update-locker-combination)
|
||||
* [Enable Student Account](#enable-student-account)
|
||||
* [Enable Teacher Acccount](#enable-teacher-account)
|
||||
|
||||
<br>
|
||||
|
||||
@@ -151,7 +158,9 @@ There are several account that can be registered into the system. As you may gue
|
||||
"firstname": "John",
|
||||
"lastname": "Doe",
|
||||
"dob": "01-01-1999",
|
||||
"email": "john_doe@example.com"
|
||||
"email": "john_doe@example.com",
|
||||
"password1": "mySuperSecurePassword",
|
||||
"password2": "mySuperSecurePassword"
|
||||
}
|
||||
```
|
||||
|
||||
@@ -181,10 +190,15 @@ There are several account that can be registered into the system. As you may gue
|
||||
```jsonc
|
||||
{
|
||||
"firstname": "Homer",
|
||||
"middlename": "Jay",
|
||||
"lastname": "Simson",
|
||||
"dob": "12-05-1956",
|
||||
"email": "homerdog_simpson@example.com"
|
||||
"middlename": "Jay", // (optional)
|
||||
"lastname": "Simpson",
|
||||
"province": "...", // (optional)
|
||||
"city": "Springfield", // (optional)
|
||||
"postal": "...", // (optional)
|
||||
"dob": "12-05-1956", // (optional)
|
||||
"email": "homer_simpson@example.com",
|
||||
"password1": "homerLovesDuffBeer123",
|
||||
"password2": "homerLovesDuffBeer123"
|
||||
}
|
||||
```
|
||||
|
||||
@@ -212,15 +226,18 @@ There are several account that can be registered into the system. As you may gue
|
||||
```jsonc
|
||||
{
|
||||
"firstname": "Bart",
|
||||
"middlename": "JoJo",
|
||||
"middlename": "JoJo", // (optional)
|
||||
"lastname": "Simpson",
|
||||
"age": 10,
|
||||
"gradelevel": 4,
|
||||
"dob": "17-12-1979",
|
||||
"email": "bartsimpson@example.com",
|
||||
"province": "...",
|
||||
"city": "Springfield",
|
||||
"address": "742 Evergreen Terrace",
|
||||
"postal": "..."
|
||||
"postal": "...",
|
||||
"password1": "I_am_el_barto_5",
|
||||
"password2": "I_am_el_barto_5"
|
||||
}
|
||||
```
|
||||
|
||||
@@ -230,7 +247,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
```jsonc
|
||||
{
|
||||
"success": true,
|
||||
"successfully inserted student"
|
||||
"message": "successfully inserted student"
|
||||
}
|
||||
```
|
||||
|
||||
@@ -243,7 +260,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
|
||||
4. Accounts are given a default profile image. This can be updated in the future.
|
||||
|
||||
**(Coming Soon)**
|
||||
**(Currently No verified email required)**
|
||||
5. All new users, once have verified their email, will receive and email containing their ID.
|
||||
|
||||
**(Currently No verified email required)**
|
||||
@@ -263,7 +280,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"tid": "123456",
|
||||
"uid": "123456",
|
||||
"password": "myawesomepassword123"
|
||||
}
|
||||
```
|
||||
@@ -271,7 +288,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```
|
||||
```jsonc
|
||||
{
|
||||
"success": true,
|
||||
"message": "correct password"
|
||||
@@ -290,7 +307,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"tid": "123456",
|
||||
"uid": "123456",
|
||||
"password": "myawesomepassword123"
|
||||
}
|
||||
```
|
||||
@@ -317,7 +334,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"sid": "123456",
|
||||
"uid": "123456",
|
||||
"password": "myawesomepassword123"
|
||||
}
|
||||
```
|
||||
@@ -415,7 +432,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"sid": "123456",
|
||||
"uid": "123456",
|
||||
"firstname": "Lisa",
|
||||
"middlename": "Marie", // (OPTIONAL)
|
||||
"lastname": "Simpson"
|
||||
@@ -445,7 +462,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
* JSON":
|
||||
```jsonc
|
||||
{
|
||||
"sid": "123456",
|
||||
"uid": "123456",
|
||||
"gradelevel": 11
|
||||
}
|
||||
```
|
||||
@@ -473,7 +490,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"sid": "123456",
|
||||
"uid": "123456",
|
||||
"homeroom": "A123"
|
||||
}
|
||||
```
|
||||
@@ -501,7 +518,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"sid": "123456",
|
||||
"uid": "123456",
|
||||
"lockernumber": "B123"
|
||||
}
|
||||
```
|
||||
@@ -529,7 +546,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"sid": "123456",
|
||||
"uid": "123456",
|
||||
"yog": 2020
|
||||
}
|
||||
```
|
||||
@@ -589,7 +606,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"sid": "123456", // (Only required if signed in as admin)
|
||||
"uid": "123456", // (Only required if signed in as admin)
|
||||
"email": "BartSimpsonsCoolEmail@example.com"
|
||||
}
|
||||
```
|
||||
@@ -617,7 +634,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"sid": "123456",
|
||||
"uid": "123456",
|
||||
"address": "742 Evergreen Terrace",
|
||||
"city": "Springfield",
|
||||
"province": "...",
|
||||
@@ -674,7 +691,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"tid": "123456",
|
||||
"uid": "123456",
|
||||
"firstname": "Marjorie",
|
||||
"middlename": "Jacqueline", // (Optional)
|
||||
"lastname": "Simpson"
|
||||
@@ -702,9 +719,9 @@ There are several account that can be registered into the system. As you may gue
|
||||
**Required:**
|
||||
* Logged into an admin account
|
||||
* JSON:
|
||||
```
|
||||
```jsonc
|
||||
{
|
||||
"tid": "123456",
|
||||
"uid": "123456",
|
||||
"homeroom": "A123"
|
||||
}
|
||||
```
|
||||
@@ -764,7 +781,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"tid": "123456", // (Only required if igned in as admin)
|
||||
"uid": "123456", // (Only required if igned in as admin)
|
||||
"email": "MargeSimpson@example.com"
|
||||
}
|
||||
```
|
||||
@@ -792,7 +809,7 @@ There are several account that can be registered into the system. As you may gue
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"tid": "123456",
|
||||
"uid": "123456",
|
||||
"address": "742 Evergreen Terrace",
|
||||
"city": "Springfield",
|
||||
"province": "...",
|
||||
@@ -839,83 +856,414 @@ There are several account that can be registered into the system. As you may gue
|
||||
<br></br>
|
||||
|
||||
+ ### Update Admin Name
|
||||
**Coming Soon...**
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/admin/updateName
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into the admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"firstname": "Seymour",
|
||||
"lastname": "Skinner"
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": "true",
|
||||
"message": "successfully updated admin"
|
||||
}
|
||||
```
|
||||
|
||||
<br></br>
|
||||
|
||||
+ ### Update Admin Password
|
||||
**Coming Soon...**
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/admin/updateEmail
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into the admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"email": "seymour_skinner@example.com"
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": "true",
|
||||
"message": "successfully updated admin"
|
||||
}
|
||||
```
|
||||
|
||||
<br></br>
|
||||
|
||||
+ ### Update Admin Email
|
||||
**Coming Soon...**
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/admin/updatePassword
|
||||
```
|
||||
|
||||
<br></br>
|
||||
**Required:**
|
||||
* Logged into the admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"password": "myOldPassword",
|
||||
"newpassword1": "myNewPassword",
|
||||
"newpassword2": "myNewPassword"
|
||||
}
|
||||
```
|
||||
|
||||
+ ### Update Admin Photo
|
||||
**Coming Soon...**
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": "true",
|
||||
"message": "successfully updated admin password"
|
||||
}
|
||||
```
|
||||
* Emails admin an alert of password change
|
||||
|
||||
<br></br>
|
||||
|
||||
## Managing Conacts
|
||||
**To be Documented...**
|
||||
In the case of an emergency for a specified student, a contact is required to be alerted during a situation. There can be multiple contacts with ranging priorities to ensure the correct person(s) are reached.
|
||||
|
||||
+ ### Creating Contact
|
||||
**To be Documented...**
|
||||
+ ### Create Contact
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/contact/createContact
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into the admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"uid": "123456",
|
||||
"firstname": "Marge",
|
||||
"middlename": "Jacqueline", // (optional)
|
||||
"lastname": "Simpson",
|
||||
"homephone": "123-456-7890",
|
||||
"workphone": "098-765-4321",
|
||||
"email": "therealmarge@example.com",
|
||||
"priority": 1, // 1 is highest priority, 10 is least priority
|
||||
"relation": "mother",
|
||||
"province": "...", // (optional)
|
||||
"city": "Springfield", // (optional)
|
||||
"address": "742 Evergreen Terrace", // (optional)
|
||||
"postal": "..." // (optional)
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": "true",
|
||||
"message": "successfully inserted contact to student"
|
||||
}
|
||||
```
|
||||
* Emails admin an alert of password change
|
||||
|
||||
<br></br>
|
||||
|
||||
+ ### Update Contact Name
|
||||
**To be Documented...**
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/contact/updateName
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into the admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"_id": "<contact object id>",
|
||||
"firstname": "Marge",
|
||||
"middlename": "", // (optional)
|
||||
"lastname": "Simpson"
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": "true",
|
||||
"message": "successfully updated contact"
|
||||
}
|
||||
```
|
||||
|
||||
<br></br>
|
||||
|
||||
+ ### Update Contact Address
|
||||
**To be Documented...**
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/contact/updateAddress
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into the admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"_id": "<contact object id>",
|
||||
"address": "742 Evergreen Terrace",
|
||||
"city": "Springfield",
|
||||
"province": "...",
|
||||
"postal": "..."
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": "true",
|
||||
"message": "successfully updated contact"
|
||||
}
|
||||
```
|
||||
|
||||
<br></br>
|
||||
|
||||
+ ### Update Contact Home Phone
|
||||
**To be Documented...**
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/contact/updateHomePhone
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into the admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"_id": "<contact object id>",
|
||||
"newnumber": "123-456-7890"
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": "true",
|
||||
"message": "successfully updated contact"
|
||||
}
|
||||
```
|
||||
|
||||
<br></br>
|
||||
|
||||
+ ### Update Contact Work Phone
|
||||
**To be Documented...**
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/contact/updateWorkPhone
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into the admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"_id": "<contact object id>",
|
||||
"newnumber": "123-456-7890"
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": "true",
|
||||
"message": "successfully updated contact"
|
||||
}
|
||||
```
|
||||
|
||||
<br></br>
|
||||
|
||||
+ ### Update Contact Email
|
||||
**To be Documented...**
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/contact/updateEmail
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into the admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"_id": "<contact object id>",
|
||||
"email": "marge_simpson@example.com"
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": "true",
|
||||
"message": "successfully updated contact"
|
||||
}
|
||||
```
|
||||
|
||||
<br></br>
|
||||
|
||||
+ ### Update Contact Priority
|
||||
**To be Documented...**
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/contact/updatePriority
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into the admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"_id": "<contact object id>",
|
||||
"priority": 1 // 1: highest priority, 10 lowest priority
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": "true",
|
||||
"message": "successfully updated contact"
|
||||
}
|
||||
```
|
||||
|
||||
<br></br>
|
||||
|
||||
+ ### Delete Conotact
|
||||
**To be Documented...**
|
||||
+ ### Delete Contact
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/contact/deleteContact
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into the admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"_id": "<contact object id>"
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": "true",
|
||||
"message": "successfully deleted contact"
|
||||
}
|
||||
```
|
||||
|
||||
<br></br>
|
||||
|
||||
## Remove Users
|
||||
**To be Documented...**
|
||||
Students and staff are bound to leave the school at some time, so there is a way to remove them from the sytem database permanetly for any case.
|
||||
|
||||
+ ### Remove Admin
|
||||
**To be Documented...**
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/remove/admin
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into an admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"uid": "123456"
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": true,
|
||||
"message": "successfully deleted admin"
|
||||
}
|
||||
```
|
||||
|
||||
<br></br>
|
||||
|
||||
+ ### Remove Teacher
|
||||
**To be Documented...**
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/remove/teacher
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into an admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"uid": "123456"
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": true,
|
||||
"message": "successfully deleted teacher"
|
||||
}
|
||||
```
|
||||
|
||||
<br></br>
|
||||
|
||||
+ ### Remove Student
|
||||
**To be Documented...**
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/remove/student
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into an admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"uid": "123456"
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": true,
|
||||
"message": "successfully deleted student"
|
||||
}
|
||||
```
|
||||
|
||||
<br></br>
|
||||
|
||||
@@ -923,18 +1271,87 @@ There are several account that can be registered into the system. As you may gue
|
||||
Administrators play a very important role in managing a school, they do much work behind the scenes to make sure that everything is correctly organized and working.
|
||||
|
||||
+ ### Update Locker Combination
|
||||
**To be Documented...**
|
||||
It is likely a school changes out their lockers, swapping the locks randomly. In the case a locker requires a combination change in the database, admins can update the locker database via this API endpoint.
|
||||
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/admin/updateLockerCombo
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into an admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"lockernumber": "B461",
|
||||
"newlockercombo": "51-21-49"
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": true,
|
||||
"message": "successfully updated locker"
|
||||
}
|
||||
```
|
||||
|
||||
<br></br>
|
||||
|
||||
+ ### Enable Student Account
|
||||
In the case a students acount has been disabled, an admin would require to enable the account.
|
||||
|
||||
**To be Documented...**
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/admin/enableStudent
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into an admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"uid": "123456"
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": true,
|
||||
"message": "successfully enabled student account"
|
||||
}
|
||||
```
|
||||
<br></br>
|
||||
|
||||
+ ### Enable Teacher Account
|
||||
In the case a teachers acount has been disabled, an admin would require to enable the account.
|
||||
|
||||
**To be Documented...**
|
||||
**Method:** `POST`
|
||||
```
|
||||
<API_URL>/api/v1/admin/enableTeacher
|
||||
```
|
||||
|
||||
**Required:**
|
||||
* Logged into an admin
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"uid": "123456"
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
* Status 200: `OK`
|
||||
* JSON:
|
||||
```jsonc
|
||||
{
|
||||
"success": true,
|
||||
"message": "successfully enabled teacher account"
|
||||
}
|
||||
```
|
||||
<br></br>
|
||||
@@ -5,11 +5,15 @@ The backend API for a school management system accessible by staff and students.
|
||||
***Explore the docs »***
|
||||
* [Getting Started](#getting-started)
|
||||
* [Usage/Documenation](#usage)
|
||||
* [Contributing](#contributing)
|
||||
* [License](#license)
|
||||
* [Contact](#contact)
|
||||
<br>
|
||||
<br>
|
||||
|
||||
### Built With
|
||||
|
||||
* [Golang](https://go.dev/)
|
||||
* [GoFiber](https://gofiber.io/)
|
||||
* [GoMongo Driver](https://docs.mongodb.com/drivers/go/current/)
|
||||
* [golang-jwt](https://github.com/golang-jwt/jwt)
|
||||
|
||||
## About The Project
|
||||
|
||||
@@ -19,22 +23,31 @@ this on as a full project to work on for my Software Engineering class and is no
|
||||
work on this till completion, starting with this API, and then the front end, learning new tricks and languages
|
||||
along the way.
|
||||
|
||||
I highly recommend looking at the testing for [schedule generation](/test/scheduleGenerator), [version 3](/test/scheduleGenerator/generator_v3.py)
|
||||
Developing the API has has me face many challenges. With me developing my techniques in Go, and increasing my
|
||||
ability to work with Go frameworks. Understanding the workflow of packages and the Go ecosystem.
|
||||
|
||||
I started by developing authentication; a solid footing to the project, without the authentication of users,
|
||||
the rest of the project would fail to work. As the purpose of this API handles sensitive data on students.
|
||||
|
||||
Once the authentication was complete, I took to working on majority of the user data handling. Such as
|
||||
setting, updating and or deleting user attributes. Building a few more key authentication features only
|
||||
allowing the proper authenticated user, an admin, perfom many of the actions.
|
||||
|
||||
Once this was complete I started work on conceptualizing the next major step of the API. Course management,
|
||||
including course selection, schedule generation, etc. This can be viewed in this [request](https://github.com/SowinskiBraeden/school-management-api/issues/5).
|
||||
To start off on this new set of features, I decided to tackle the largest and most complex problem,
|
||||
schedule generation. This algorithm generates a master timetable as well as updates the student schedule.
|
||||
All the while keeping track of any errors for admins to handle personally. This can be found in `testing`,
|
||||
The [schedule generation](/test/scheduleGenerator) file is of the latest version, version 3. Though this has
|
||||
been moved to its own [repository](https://github.com/SowinskiBraeden/ScheduleGeneratorApp).
|
||||
|
||||
## Related Work
|
||||
|
||||
After the majority completion of vital api functionalities such as the ability to update information, create new
|
||||
information, generate information, delete information, authentication etc. I have created a new repository
|
||||
for the next frontier of this project. I am now concurrently working on the [School Management Website](https://github.com/SowinskiBraeden/school-management).
|
||||
for the next frontier of this project. I am now concurrently working on the [School Management Website](https://github.com/SowinskiBraeden/school-management-vue).
|
||||
|
||||
The School Management Website. is going to be written using the [Vue.js](https://vuejs.org/) framework. Vue.js is a popular framwork for working on frontend UI programs. I am currently unfamiliar with the framework but plan on learning the framework to use it more in the future.
|
||||
<br>
|
||||
|
||||
### Built With
|
||||
|
||||
* [Golang](https://go.dev/)
|
||||
* [GoFiber](https://gofiber.io/)
|
||||
* [GoMongo Driver](https://docs.mongodb.com/drivers/go/current/)
|
||||
The School Management Website, is going to be written using the [Vue.js](https://vuejs.org/) framework as there were issues trying to use Next.js in an [older test](https://github.com/SowinskiBraeden/school-management).
|
||||
|
||||
## Getting Started
|
||||
|
||||
@@ -90,13 +103,6 @@ The usage for this API is in the name, school management, it's not an easy task
|
||||
To see a full list of features and how to use the system, read the [documentation](DOCUMENTATION.md)
|
||||
|
||||
|
||||
<!-- CONTRIBUTING -->
|
||||
## Contributing
|
||||
|
||||
Please refer to [CONTRIBUTING](CONTRIBUTING.md) for contributing to the project.
|
||||
|
||||
|
||||
|
||||
<!-- LICENSE -->
|
||||
## License
|
||||
|
||||
@@ -106,6 +112,6 @@ Distributed under the MIT License. See [LICENSE](LICENSE) for more information.
|
||||
<!-- CONTACT -->
|
||||
## Contact
|
||||
|
||||
Braeden Sowinski - [@BraedenSowinski](https://twitter.com/BraedenSowinski) - sowinskibraeden@gmail.com
|
||||
Braeden Sowinski - [@BraedenSowinski](https://twitter.com/BraedenSowinski) - sowinskibraeden@gmail.com - McDazzzled#5307 on Discord
|
||||
|
||||
Project Link: [https://github.com/SowinskiBraeden/school-management-api](https://github.com/SowinskiBraeden/school-management-api)
|
||||
+461
-155
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/mail"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -21,10 +22,29 @@ import (
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
var teacherCollection *mongo.Collection = database.OpenCollection(database.Client, "teachers")
|
||||
var studentCollection *mongo.Collection = database.OpenCollection(database.Client, "students")
|
||||
var contactCollection *mongo.Collection = database.OpenCollection(database.Client, "contacts")
|
||||
var adminCollection *mongo.Collection = database.OpenCollection(database.Client, "admins")
|
||||
/*
|
||||
The auth controller handles the following:
|
||||
- default admin settings
|
||||
- creating new users
|
||||
- authenticating users
|
||||
- retreiving users
|
||||
- removeing users
|
||||
*/
|
||||
|
||||
var TeacherCollection *mongo.Collection = database.OpenCollection(database.Client, "teachers")
|
||||
var StudentCollection *mongo.Collection = database.OpenCollection(database.Client, "students")
|
||||
var ContactCollection *mongo.Collection = database.OpenCollection(database.Client, "contacts")
|
||||
var AdminCollection *mongo.Collection = database.OpenCollection(database.Client, "admins")
|
||||
var ImageCollection *mongo.Collection = database.OpenCollection(database.Client, "images")
|
||||
var LockerCollection *mongo.Collection = database.OpenCollection(database.Client, "lockers")
|
||||
|
||||
func validMailAddress(address string) (string, bool) {
|
||||
addr, err := mail.ParseAddress(address)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
return addr.Address, true
|
||||
}
|
||||
|
||||
func confirm(s string) bool {
|
||||
r := bufio.NewReader(os.Stdin)
|
||||
@@ -63,7 +83,16 @@ func CreateDefaultAdmin() models.Admin {
|
||||
admin.LastName = lastname
|
||||
admin.Email = email
|
||||
|
||||
admin.SchoolEmail = admin.GenerateSchoolEmail()
|
||||
var schoolEmail string = ""
|
||||
offset := 0
|
||||
for {
|
||||
schoolEmail = admin.GenerateSchoolEmail(offset, schoolEmail)
|
||||
if !admin.EmailExists(schoolEmail) {
|
||||
break
|
||||
}
|
||||
offset++
|
||||
}
|
||||
admin.SchoolEmail = schoolEmail
|
||||
|
||||
pass := strings.TrimSuffix(string(password), "\n")
|
||||
admin.Password = admin.HashPassword(pass)
|
||||
@@ -72,7 +101,7 @@ func CreateDefaultAdmin() models.Admin {
|
||||
var aid string
|
||||
for {
|
||||
aid = GenerateID(6)
|
||||
if ValidateID(aid, 3) == true {
|
||||
if ValidateID(aid, 3) {
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -86,7 +115,7 @@ func CreateDefaultAdmin() models.Admin {
|
||||
}
|
||||
|
||||
func NewSystem() {
|
||||
count, err := adminCollection.CountDocuments(context.Background(), bson.D{})
|
||||
count, err := AdminCollection.CountDocuments(context.Background(), bson.D{})
|
||||
if err != nil {
|
||||
fmt.Println("Unable to detect new system")
|
||||
}
|
||||
@@ -98,7 +127,7 @@ func NewSystem() {
|
||||
defaultAdmin := CreateDefaultAdmin()
|
||||
|
||||
if confirm("Are the above credentials correct?") {
|
||||
_, insertErr := adminCollection.InsertOne(context.Background(), defaultAdmin)
|
||||
_, insertErr := AdminCollection.InsertOne(context.Background(), defaultAdmin)
|
||||
if insertErr != nil {
|
||||
log.Printf("Failed to create an admin\n")
|
||||
}
|
||||
@@ -113,9 +142,6 @@ func NewSystem() {
|
||||
|
||||
var SecretKey = os.Getenv("secret")
|
||||
|
||||
var systemEmail string = os.Getenv("SYSTEM_EMAIL")
|
||||
var systemPassword string = os.Getenv("SYSTEM_PASSWORD")
|
||||
|
||||
func AuthenticateUser(c *fiber.Ctx, userType int) (bool, string) {
|
||||
if userType < 1 || userType > 3 {
|
||||
log.Fatal("Invalid userType")
|
||||
@@ -133,7 +159,7 @@ func AuthenticateUser(c *fiber.Ctx, userType int) (bool, string) {
|
||||
claims := token.Claims.(*jwt.StandardClaims)
|
||||
|
||||
var userID models.Id
|
||||
findErr := idCollection.FindOne(context.TODO(), bson.M{"cid": claims.Issuer}).Decode(&userID)
|
||||
findErr := IdCollection.FindOne(context.TODO(), bson.M{"cid": claims.Issuer}).Decode(&userID)
|
||||
if findErr != nil {
|
||||
return false, ""
|
||||
}
|
||||
@@ -168,7 +194,10 @@ func Enroll(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// Check minimum enroll field requirements are met
|
||||
if data["firstname"] == nil || data["lastname"] == nil || data["age"] == nil || data["gradelevel"] == nil || data["dob"] == nil || data["email"] == nil || data["province"] == nil || data["city"] == nil || data["address"] == nil || data["postal"] == nil {
|
||||
if data["firstname"] == nil || data["lastname"] == nil || data["age"] == nil ||
|
||||
data["gradelevel"] == nil || data["dob"] == nil || data["email"] == nil ||
|
||||
data["province"] == nil || data["city"] == nil || data["address"] == nil ||
|
||||
data["postal"] == nil || data["password1"] == nil || data["password2"] == nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
@@ -176,20 +205,47 @@ func Enroll(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
if _, validEmail := validMailAddress(data["email"].(string)); !validEmail {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "invalid email address",
|
||||
})
|
||||
}
|
||||
|
||||
if data["password1"] != data["password2"] {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the passwords chosen must match",
|
||||
})
|
||||
}
|
||||
|
||||
var student models.Student
|
||||
student.PersonalData.FirstName = data["firstname"].(string)
|
||||
student.PersonalData.MiddleName = data["middlename"].(string)
|
||||
student.PersonalData.LastName = data["lastname"].(string)
|
||||
student.PersonalData.Age = data["age"].(float64)
|
||||
student.SchoolData.GradeLevel = data["gradelevel"].(float64)
|
||||
student.PersonalData.DOB = data["dob"].(string)
|
||||
student.PersonalData.Email = data["email"].(string)
|
||||
student.PersonalData.Province = data["province"].(string)
|
||||
student.PersonalData.City = data["city"].(string)
|
||||
student.PersonalData.Address = data["address"].(string)
|
||||
student.PersonalData.Postal = data["postal"].(string)
|
||||
student.PersonalData.Contacts = []string{}
|
||||
student.SchoolData.YOG = ((12 - int(student.SchoolData.GradeLevel)) + time.Now().Year()) + 1
|
||||
|
||||
if !student.CheckPasswordStrength(data["password1"].(string)) {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "your password isnt strong enough",
|
||||
})
|
||||
}
|
||||
|
||||
student.Personal.FirstName = data["firstname"].(string)
|
||||
if middle, ok := data["middlename"]; ok {
|
||||
student.Personal.MiddleName = middle.(string)
|
||||
}
|
||||
student.Personal.LastName = data["lastname"].(string)
|
||||
student.Personal.Age = data["age"].(float64)
|
||||
student.School.GradeLevel = data["gradelevel"].(float64)
|
||||
student.Personal.DOB = data["dob"].(string)
|
||||
student.Personal.Email = data["email"].(string)
|
||||
student.Personal.Province = data["province"].(string)
|
||||
student.Personal.City = data["city"].(string)
|
||||
student.Personal.Address = data["address"].(string)
|
||||
student.Personal.Postal = data["postal"].(string)
|
||||
student.Personal.Contacts = []string{}
|
||||
student.School.YOG = ((12 - int(student.School.GradeLevel)) + time.Now().Year()) + 1
|
||||
|
||||
var photo models.Photo
|
||||
photo.Name = uuid.New().String()
|
||||
@@ -200,7 +256,7 @@ func Enroll(c *fiber.Ctx) error {
|
||||
defaultImage, _ := os.ReadFile("./database/defaultImage.txt")
|
||||
photo.Base64 = string(defaultImage)
|
||||
|
||||
student.SchoolData.PhotoName = photo.Name
|
||||
student.School.PhotoName = photo.Name
|
||||
|
||||
var schoolEmail string = ""
|
||||
offset := 0
|
||||
@@ -211,55 +267,53 @@ func Enroll(c *fiber.Ctx) error {
|
||||
}
|
||||
offset++
|
||||
}
|
||||
student.AccountData.SchoolEmail = schoolEmail
|
||||
student.AccountData.HashHistory = []string{}
|
||||
student.Account.SchoolEmail = schoolEmail
|
||||
student.Account.HashHistory = []string{}
|
||||
|
||||
// Disable login block
|
||||
student.AccountData.AccountDisabled = false
|
||||
student.AccountData.Alerted = false
|
||||
student.AccountData.Attempts = 0
|
||||
student.Account.AccountDisabled = false
|
||||
student.Account.Alerted = false
|
||||
student.Account.Attempts = 0
|
||||
|
||||
// Generate temporary password
|
||||
var tempPass string = student.GeneratePassword(12, 1, 1, 1)
|
||||
student.AccountData.Password = student.HashPassword(tempPass)
|
||||
student.AccountData.TempPassword = true
|
||||
|
||||
// Send student personal email temp password
|
||||
subject := "Password Changed"
|
||||
receiver := student.PersonalData.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/passwordChanged.html", map[string]string{"username": student.PersonalData.FirstName, "password": tempPass}); !sent {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Could not send password to students email",
|
||||
})
|
||||
}
|
||||
student.Account.Password = student.HashPassword(data["password1"].(string))
|
||||
student.Account.TempPassword = false
|
||||
|
||||
var sid string
|
||||
for {
|
||||
sid = GenerateID(6)
|
||||
if ValidateID(sid, 1) == true {
|
||||
if ValidateID(sid, 1) {
|
||||
break
|
||||
}
|
||||
}
|
||||
student.SchoolData.SID = sid
|
||||
student.School.SID = sid
|
||||
|
||||
// Send student personal email student ID
|
||||
subject := "Account Registered"
|
||||
receiver := student.Personal.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/accountRegistered.html", map[string]string{"username": student.Personal.FirstName, "id": sid, "userType": "student"}); !sent {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Could not send ID to students email",
|
||||
})
|
||||
}
|
||||
|
||||
var pen string
|
||||
for {
|
||||
pen = GenerateID(9)
|
||||
if ValidatePEN(pen) == true {
|
||||
if ValidatePEN(pen) {
|
||||
break
|
||||
}
|
||||
}
|
||||
student.SchoolData.PEN = pen
|
||||
student.School.PEN = pen
|
||||
|
||||
student.Created_at, _ = time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
student.Updated_at, _ = time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
student.ID = primitive.NewObjectID()
|
||||
|
||||
_, insertErr := studentCollection.InsertOne(ctx, student)
|
||||
_, insertErr := StudentCollection.InsertOne(ctx, student)
|
||||
if insertErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
@@ -269,7 +323,7 @@ func Enroll(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
_, insertErr = imageCollection.InsertOne(ctx, photo)
|
||||
_, insertErr = ImageCollection.InsertOne(ctx, photo)
|
||||
if insertErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
@@ -309,7 +363,8 @@ func RegisterTeacher(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// Check minimum register teacher field requirements are met
|
||||
if data["firstname"] == nil || data["lastname"] == nil || data["dob"] == nil || data["email"] == nil {
|
||||
if data["firstname"] == nil || data["lastname"] == nil || data["dob"] == nil || data["email"] == nil ||
|
||||
data["password1"] == nil || data["password2"] == nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
@@ -317,15 +372,50 @@ func RegisterTeacher(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
if _, validEmail := validMailAddress(data["email"].(string)); !validEmail {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "invalid email address",
|
||||
})
|
||||
}
|
||||
|
||||
if data["password1"] != data["password2"] {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the passwords chosen must match",
|
||||
})
|
||||
}
|
||||
|
||||
var teacher models.Teacher
|
||||
teacher.PersonalData.FirstName = data["firstname"].(string)
|
||||
teacher.PersonalData.MiddleName = data["middlename"].(string)
|
||||
teacher.PersonalData.LastName = data["lastname"].(string)
|
||||
teacher.PersonalData.Email = data["email"].(string)
|
||||
teacher.PersonalData.Province = data["province"].(string)
|
||||
teacher.PersonalData.City = data["city"].(string)
|
||||
teacher.PersonalData.Postal = data["postal"].(string)
|
||||
teacher.PersonalData.DOB = data["dob"].(string)
|
||||
|
||||
if !teacher.CheckPasswordStrength(data["password1"].(string)) {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "your password isnt strong enough",
|
||||
})
|
||||
}
|
||||
|
||||
teacher.Personal.FirstName = data["firstname"].(string)
|
||||
if middle, ok := data["middlename"]; ok {
|
||||
teacher.Personal.MiddleName = middle.(string)
|
||||
}
|
||||
teacher.Personal.LastName = data["lastname"].(string)
|
||||
teacher.Personal.Email = data["email"].(string)
|
||||
if province, ok := data["province"]; ok {
|
||||
teacher.Personal.Province = province.(string)
|
||||
}
|
||||
if city, ok := data["city"]; ok {
|
||||
teacher.Personal.City = city.(string)
|
||||
}
|
||||
if postal, ok := data["postal"]; ok {
|
||||
teacher.Personal.Postal = postal.(string)
|
||||
}
|
||||
if dob, ok := data["dob"]; ok {
|
||||
teacher.Personal.DOB = dob.(string)
|
||||
}
|
||||
|
||||
var photo models.Photo
|
||||
photo.Name = uuid.New().String()
|
||||
@@ -336,7 +426,7 @@ func RegisterTeacher(c *fiber.Ctx) error {
|
||||
defaultImage, _ := os.ReadFile("./database/defaultImage.txt")
|
||||
photo.Base64 = string(defaultImage)
|
||||
|
||||
teacher.SchoolData.PhotoName = photo.Name
|
||||
teacher.School.PhotoName = photo.Name
|
||||
|
||||
var schoolEmail string = ""
|
||||
offset := 0
|
||||
@@ -347,46 +437,44 @@ func RegisterTeacher(c *fiber.Ctx) error {
|
||||
}
|
||||
offset++
|
||||
}
|
||||
teacher.AccountData.SchoolEmail = schoolEmail
|
||||
teacher.AccountData.HashHistory = []string{}
|
||||
teacher.Account.SchoolEmail = schoolEmail
|
||||
teacher.Account.HashHistory = []string{}
|
||||
|
||||
// Disable login block
|
||||
teacher.AccountData.AccountDisabled = false
|
||||
teacher.AccountData.Attempts = 0
|
||||
teacher.Account.AccountDisabled = false
|
||||
teacher.Account.Attempts = 0
|
||||
|
||||
var tempPass string = teacher.GeneratePassword(12, 1, 1, 1)
|
||||
teacher.AccountData.Password = teacher.HashPassword(tempPass)
|
||||
teacher.AccountData.TempPassword = true
|
||||
|
||||
// Send teacher personal email temp password
|
||||
subject := "Password Changed"
|
||||
receiver := teacher.PersonalData.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/passwordChanged.html", map[string]string{"username": teacher.PersonalData.FirstName, "password": tempPass}); !sent {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Could not send password to teachers email",
|
||||
})
|
||||
}
|
||||
teacher.Account.Password = teacher.HashPassword(data["password1"].(string))
|
||||
teacher.Account.TempPassword = false
|
||||
|
||||
var tid string
|
||||
// For the unlikely event that an ID is already in use this will simply try again till it gets a id not in use
|
||||
for {
|
||||
tid = GenerateID(6)
|
||||
isValid := ValidateID(tid, 2)
|
||||
if isValid == true {
|
||||
if ValidateID(tid, 2) {
|
||||
break
|
||||
}
|
||||
}
|
||||
teacher.SchoolData.TID = tid
|
||||
teacher.School.TID = tid
|
||||
|
||||
// Send teacher personal email student ID
|
||||
subject := "Account Registered"
|
||||
receiver := teacher.Personal.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/accountRegistered.html", map[string]string{"username": teacher.Personal.FirstName, "id": tid, "userType": "teacher"}); !sent {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Could not send ID to teachers email",
|
||||
})
|
||||
}
|
||||
|
||||
teacher.Created_at, _ = time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
teacher.Updated_at, _ = time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
teacher.ID = primitive.NewObjectID()
|
||||
|
||||
_, insertErr := teacherCollection.InsertOne(ctx, teacher)
|
||||
_, insertErr := TeacherCollection.InsertOne(ctx, teacher)
|
||||
if insertErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
@@ -426,7 +514,8 @@ func CreateAdmin(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// Check minimum register teacher field requirements are met
|
||||
if data["firstname"] == nil || data["lastname"] == nil || data["dob"] == nil || data["email"] == nil {
|
||||
if data["firstname"] == nil || data["lastname"] == nil || data["dob"] == nil || data["email"] == nil ||
|
||||
data["password1"] == nil || data["password2"] == nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
@@ -434,44 +523,77 @@ func CreateAdmin(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
if _, validEmail := validMailAddress(data["email"].(string)); !validEmail {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "invalid email address",
|
||||
})
|
||||
}
|
||||
|
||||
if data["password1"] != data["password2"] {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the passwords chosen must match",
|
||||
})
|
||||
}
|
||||
|
||||
var admin models.Admin
|
||||
|
||||
if !admin.CheckPasswordStrength(data["password1"].(string)) {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "your password isnt strong enough",
|
||||
})
|
||||
}
|
||||
|
||||
admin.FirstName = data["firstname"].(string)
|
||||
admin.LastName = data["lastname"].(string)
|
||||
admin.Email = data["email"].(string)
|
||||
|
||||
admin.SchoolEmail = admin.GenerateSchoolEmail()
|
||||
|
||||
tempPass := admin.GeneratePassword(12, 1, 1, 1)
|
||||
admin.Password = admin.HashPassword(tempPass)
|
||||
admin.TempPassword = true
|
||||
|
||||
// Send admin personal email temp password
|
||||
subject := "Password Changed"
|
||||
receiver := admin.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/passwordChanged.html", map[string]string{"username": admin.FirstName, "password": tempPass}); !sent {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Could not send password to students email",
|
||||
})
|
||||
var schoolEmail string = ""
|
||||
offset := 0
|
||||
for {
|
||||
schoolEmail = admin.GenerateSchoolEmail(offset, schoolEmail)
|
||||
if !admin.EmailExists(schoolEmail) {
|
||||
break
|
||||
}
|
||||
offset++
|
||||
}
|
||||
admin.SchoolEmail = schoolEmail
|
||||
|
||||
admin.Password = admin.HashPassword(data["password1"].(string))
|
||||
admin.TempPassword = false
|
||||
|
||||
var aid string
|
||||
for {
|
||||
aid = GenerateID(6)
|
||||
if ValidateID(aid, 3) == true {
|
||||
if ValidateID(aid, 3) {
|
||||
break
|
||||
}
|
||||
}
|
||||
admin.AID = aid
|
||||
|
||||
// Send student personal email student ID
|
||||
subject := "Account Registered"
|
||||
receiver := admin.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/accountRegistered.html", map[string]string{"username": admin.FirstName, "id": aid, "userType": "admin"}); !sent {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Could not send ID to admins email",
|
||||
})
|
||||
}
|
||||
|
||||
admin.Created_at, _ = time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
admin.Updated_at, _ = time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
admin.ID = primitive.NewObjectID()
|
||||
|
||||
_, insertErr := adminCollection.InsertOne(ctx, admin)
|
||||
_, insertErr := AdminCollection.InsertOne(ctx, admin)
|
||||
if insertErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
@@ -502,7 +624,7 @@ func StudentLogin(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["sid"] == "" || data["password"] == "" {
|
||||
if data["uid"] == "" || data["password"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
@@ -511,7 +633,7 @@ func StudentLogin(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
var student models.Student
|
||||
err := studentCollection.FindOne(ctx, bson.M{"schooldata.sid": data["sid"]}).Decode(&student)
|
||||
err := StudentCollection.FindOne(ctx, bson.M{"school.sid": data["uid"]}).Decode(&student)
|
||||
|
||||
if err != nil {
|
||||
cancel()
|
||||
@@ -524,27 +646,26 @@ func StudentLogin(c *fiber.Ctx) error {
|
||||
|
||||
var verified bool = student.ComparePasswords(data["password"])
|
||||
var localAccountDisabled bool = false
|
||||
var localAttempts int = student.AccountData.Attempts
|
||||
|
||||
if !verified {
|
||||
localAttempts += 1
|
||||
student.Account.Attempts += 1
|
||||
}
|
||||
|
||||
if student.AccountData.Attempts >= 5 || localAttempts >= 5 {
|
||||
if student.Account.Attempts >= 5 {
|
||||
localAccountDisabled = true // Catches newly disbaled account before student obj is updated
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"accountdata.accountdisabled": true,
|
||||
"accountdata.alerted": true,
|
||||
"accountdata.attempts": 0,
|
||||
"account.accountdisabled": true,
|
||||
"account.alerted": true,
|
||||
"account.attempts": 0,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := studentCollection.UpdateOne(
|
||||
_, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"schooldata.sid": data["sid"]},
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
@@ -557,15 +678,15 @@ func StudentLogin(c *fiber.Ctx) error {
|
||||
}
|
||||
}
|
||||
|
||||
if localAccountDisabled || student.AccountData.AccountDisabled {
|
||||
if localAccountDisabled || student.Account.AccountDisabled {
|
||||
|
||||
if !student.AccountData.Alerted {
|
||||
if !student.Account.Alerted {
|
||||
// Send student email warning of disabled account
|
||||
subject := "Account Disabled"
|
||||
receiver := student.PersonalData.Email
|
||||
receiver := student.Personal.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/accountDisabled.html", map[string]string{"username": student.PersonalData.FirstName}); !sent {
|
||||
if sent := r.Send("./templates/accountDisabled.html", map[string]string{"username": student.Personal.FirstName}); !sent {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
@@ -586,14 +707,14 @@ func StudentLogin(c *fiber.Ctx) error {
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"accountdata.attempts": (student.AccountData.Attempts + 1),
|
||||
"account.attempts": (student.Account.Attempts + 1),
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := studentCollection.UpdateOne(
|
||||
_, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"schooldata.sid": data["sid"]},
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
cancel()
|
||||
@@ -613,14 +734,14 @@ func StudentLogin(c *fiber.Ctx) error {
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"accountdata.attempts": 0,
|
||||
"account.attempts": 0,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := studentCollection.UpdateOne(
|
||||
_, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"schooldata.sid": data["sid"]},
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
@@ -635,7 +756,7 @@ func StudentLogin(c *fiber.Ctx) error {
|
||||
defer cancel()
|
||||
|
||||
claims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims{
|
||||
Issuer: student.SchoolData.SID,
|
||||
Issuer: student.School.SID,
|
||||
ExpiresAt: time.Now().Add(time.Hour * 24).Unix(), // 1 Day
|
||||
})
|
||||
token, err := claims.SignedString([]byte(SecretKey))
|
||||
@@ -674,7 +795,7 @@ func TeacherLogin(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["tid"] == "" || data["password"] == "" {
|
||||
if data["uid"] == "" || data["password"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
@@ -683,7 +804,7 @@ func TeacherLogin(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
var teacher models.Teacher
|
||||
err := teacherCollection.FindOne(ctx, bson.M{"schooldata.tid": data["tid"]}).Decode(&teacher)
|
||||
err := TeacherCollection.FindOne(ctx, bson.M{"school.tid": data["uid"]}).Decode(&teacher)
|
||||
defer cancel()
|
||||
|
||||
if err != nil {
|
||||
@@ -697,7 +818,7 @@ func TeacherLogin(c *fiber.Ctx) error {
|
||||
defer cancel()
|
||||
|
||||
var verified bool = teacher.ComparePasswords(data["password"])
|
||||
if verified == false {
|
||||
if !verified {
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "incorrect password",
|
||||
@@ -705,7 +826,7 @@ func TeacherLogin(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
claims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims{
|
||||
Issuer: teacher.SchoolData.TID,
|
||||
Issuer: teacher.School.TID,
|
||||
ExpiresAt: time.Now().Add(time.Hour * 24).Unix(), // 1 Day
|
||||
})
|
||||
token, err := claims.SignedString([]byte(SecretKey))
|
||||
@@ -744,7 +865,7 @@ func AdminLogin(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["aid"] == "" || data["password"] == "" {
|
||||
if data["uid"] == "" || data["password"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
@@ -753,7 +874,7 @@ func AdminLogin(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
var admin models.Admin
|
||||
err := adminCollection.FindOne(ctx, bson.M{"aid": data["aid"]}).Decode(&admin)
|
||||
err := AdminCollection.FindOne(ctx, bson.M{"aid": data["uid"]}).Decode(&admin)
|
||||
defer cancel()
|
||||
|
||||
if err != nil {
|
||||
@@ -767,7 +888,7 @@ func AdminLogin(c *fiber.Ctx) error {
|
||||
defer cancel()
|
||||
|
||||
var verified bool = admin.ComparePasswords(data["password"])
|
||||
if verified == false {
|
||||
if !verified {
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "incorrect password",
|
||||
@@ -814,13 +935,13 @@ func Student(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["sid"] == "" {
|
||||
if data["uid"] == "" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
sid = data["sid"]
|
||||
sid = data["uid"]
|
||||
} else {
|
||||
cookie := c.Cookies("jwt")
|
||||
|
||||
@@ -846,7 +967,7 @@ func Student(c *fiber.Ctx) error {
|
||||
responseData["photo"] = nil
|
||||
|
||||
var student models.Student
|
||||
findErr := studentCollection.FindOne(context.TODO(), bson.M{"schooldata.sid": sid}).Decode(&student)
|
||||
findErr := StudentCollection.FindOne(context.TODO(), bson.M{"school.sid": sid}).Decode(&student)
|
||||
if findErr != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
@@ -854,7 +975,7 @@ func Student(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
if student.AccountData.AccountDisabled {
|
||||
if student.Account.AccountDisabled {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Student Accound Disabled, Contact and Admin",
|
||||
@@ -864,15 +985,15 @@ func Student(c *fiber.Ctx) error {
|
||||
responseData["student"] = student
|
||||
|
||||
var locker models.Locker
|
||||
if student.SchoolData.Locker != "" {
|
||||
lockerCollection.FindOne(context.TODO(), bson.M{"ID": student.SchoolData.Locker}).Decode(&locker)
|
||||
if student.School.Locker != "" {
|
||||
LockerCollection.FindOne(context.TODO(), bson.M{"ID": student.School.Locker}).Decode(&locker)
|
||||
responseData["locker"] = locker
|
||||
}
|
||||
|
||||
var contacts []models.Contact
|
||||
var contact models.Contact
|
||||
for i := range student.PersonalData.Contacts {
|
||||
findErr := contactCollection.FindOne(context.TODO(), bson.M{"_id": student.PersonalData.Contacts[i]}).Decode(&contact)
|
||||
for i := range student.Personal.Contacts {
|
||||
findErr := ContactCollection.FindOne(context.TODO(), bson.M{"_id": student.Personal.Contacts[i]}).Decode(&contact)
|
||||
if findErr != nil {
|
||||
responseData["error"] = "Error! There was an error finding some contacts"
|
||||
}
|
||||
@@ -883,7 +1004,7 @@ func Student(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
var photo models.Photo
|
||||
findErr = imageCollection.FindOne(context.TODO(), bson.M{"name": student.SchoolData.PhotoName}).Decode(&photo)
|
||||
findErr = ImageCollection.FindOne(context.TODO(), bson.M{"name": student.School.PhotoName}).Decode(&photo)
|
||||
if findErr != nil {
|
||||
responseData["error"] = "Error! There was an error finding the student photo"
|
||||
}
|
||||
@@ -910,8 +1031,10 @@ func Teacher(c *fiber.Ctx) error {
|
||||
|
||||
claims := token.Claims.(*jwt.StandardClaims)
|
||||
|
||||
responseData := make(map[string]interface{})
|
||||
|
||||
var teacher models.Teacher
|
||||
findErr := teacherCollection.FindOne(context.TODO(), bson.M{"schooldata.tid": claims.Issuer}).Decode(&teacher)
|
||||
findErr := TeacherCollection.FindOne(context.TODO(), bson.M{"school.tid": claims.Issuer}).Decode(&teacher)
|
||||
if findErr != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
@@ -919,10 +1042,19 @@ func Teacher(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
responseData["teacher"] = teacher
|
||||
|
||||
var photo models.Photo
|
||||
findErr = ImageCollection.FindOne(context.TODO(), bson.M{"name": teacher.School.PhotoName}).Decode(&photo)
|
||||
if findErr != nil {
|
||||
responseData["error"] = "Error! There was an error finding the student photo"
|
||||
}
|
||||
responseData["photo"] = photo
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully logged into teacher",
|
||||
"result": teacher,
|
||||
"response": responseData,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -942,7 +1074,7 @@ func Admin(c *fiber.Ctx) error {
|
||||
claims := token.Claims.(*jwt.StandardClaims)
|
||||
|
||||
var admin models.Admin
|
||||
findErr := adminCollection.FindOne(context.TODO(), bson.M{"aid": claims.Issuer}).Decode(&admin)
|
||||
findErr := AdminCollection.FindOne(context.TODO(), bson.M{"aid": claims.Issuer}).Decode(&admin)
|
||||
if findErr != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
@@ -996,7 +1128,7 @@ func CreateContact(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["sid"] == nil || data["firstname"] == nil || data["lastname"] == nil || data["homephone"] == nil || data["email"] == nil || data["priority"] == nil || data["relation"] == nil {
|
||||
if data["uid"] == nil || data["firstname"] == nil || data["lastname"] == nil || data["homephone"] == nil || data["email"] == nil || data["priority"] == nil || data["relation"] == nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
@@ -1022,7 +1154,7 @@ func CreateContact(c *fiber.Ctx) error {
|
||||
contact.Updated_at, _ = time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
contact.ID = primitive.NewObjectID()
|
||||
|
||||
_, insertErr := contactCollection.InsertOne(ctx, contact)
|
||||
_, insertErr := ContactCollection.InsertOne(ctx, contact)
|
||||
if insertErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
@@ -1037,9 +1169,9 @@ func CreateContact(c *fiber.Ctx) error {
|
||||
"contacts": contact.ID,
|
||||
},
|
||||
}
|
||||
_, updateErr := studentCollection.UpdateOne(
|
||||
_, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"sid": data["sid"]},
|
||||
bson.M{"sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
@@ -1081,7 +1213,7 @@ func DeleteContact(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["id"] == "" {
|
||||
if data["_id"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
@@ -1089,7 +1221,7 @@ func DeleteContact(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
_, err := contactCollection.DeleteOne(ctx, bson.M{"_id": data["id"]})
|
||||
_, err := ContactCollection.DeleteOne(ctx, bson.M{"_id": data["_id"]})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
@@ -1105,3 +1237,177 @@ func DeleteContact(c *fiber.Ctx) error {
|
||||
"message": "Successfully deleted contact",
|
||||
})
|
||||
}
|
||||
|
||||
func RemoveStudent(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check student id is included
|
||||
if data["uid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
_, deleteErr := IdCollection.DeleteOne(ctx, bson.M{"cid": data["uid"]})
|
||||
if deleteErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the identification number could not be deleted",
|
||||
"error": deleteErr,
|
||||
})
|
||||
}
|
||||
|
||||
_, deleteErr = StudentCollection.DeleteOne(ctx, bson.M{"school.sid": data["uid"]})
|
||||
if deleteErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be deleted",
|
||||
"error": deleteErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully deleted student",
|
||||
})
|
||||
}
|
||||
|
||||
func RemoveTeacher(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check student id is included
|
||||
if data["uid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
_, deleteErr := IdCollection.DeleteOne(ctx, bson.M{"cid": data["uid"]})
|
||||
if deleteErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the identification number could not be deleted",
|
||||
"error": deleteErr,
|
||||
})
|
||||
}
|
||||
|
||||
_, deleteErr = TeacherCollection.DeleteOne(ctx, bson.M{"school.tid": data["uid"]})
|
||||
if deleteErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher could not be deleted",
|
||||
"error": deleteErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully deleted teacher",
|
||||
})
|
||||
}
|
||||
|
||||
func RemoveAdmin(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check student id is included
|
||||
if data["uid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
_, deleteErr := IdCollection.DeleteOne(ctx, bson.M{"cid": data["uid"]})
|
||||
if deleteErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the identification number could not be deleted",
|
||||
"error": deleteErr,
|
||||
})
|
||||
}
|
||||
|
||||
_, deleteErr = AdminCollection.DeleteOne(ctx, bson.M{"aid": data["uid"]})
|
||||
if deleteErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the admin could not be deleted",
|
||||
"error": deleteErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully deleted admin",
|
||||
})
|
||||
}
|
||||
@@ -24,7 +24,6 @@ var config Config = Config{
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
from string
|
||||
to []string
|
||||
subject string
|
||||
body string
|
||||
|
||||
@@ -14,25 +14,22 @@ import (
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
var idCollection *mongo.Collection = database.OpenCollection(database.Client, "cids")
|
||||
var IdCollection *mongo.Collection = database.OpenCollection(database.Client, "cids")
|
||||
|
||||
var table = [...]byte{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}
|
||||
|
||||
func ValidateID(id string, userType int) bool { // true: valid id, false: id already in use
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
var foundID models.Id
|
||||
err := idCollection.FindOne(ctx, bson.M{"cid": id}).Decode(&foundID)
|
||||
err := IdCollection.FindOne(ctx, bson.M{"cid": id}).Decode(&foundID)
|
||||
cancel()
|
||||
if err != nil { // If there is no id found create new ID object to be stored and return true (unless insert error then try again)
|
||||
var newID models.Id
|
||||
newID.CID = id
|
||||
newID.ParentType = userType
|
||||
newID.ID = primitive.NewObjectID()
|
||||
_, insertErr := idCollection.InsertOne(context.Background(), newID)
|
||||
if insertErr != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
_, insertErr := IdCollection.InsertOne(context.Background(), newID)
|
||||
return insertErr == nil
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -40,12 +37,9 @@ func ValidateID(id string, userType int) bool { // true: valid id, false: id alr
|
||||
func ValidatePEN(pen string) bool { // true: valid pen, false: pen already in use
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
var foundID models.Id
|
||||
err := studentCollection.FindOne(ctx, bson.M{"schooldata.pen": pen}).Decode(&foundID)
|
||||
err := StudentCollection.FindOne(ctx, bson.M{"school.pen": pen}).Decode(&foundID)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return err != nil
|
||||
}
|
||||
|
||||
func GenerateID(length int) string {
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
. "github.com/SowinskiBraeden/school-management-api/controllers"
|
||||
"github.com/SowinskiBraeden/school-management-api/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
)
|
||||
|
||||
/*
|
||||
Several of these functions aren't directly for updating admin
|
||||
information, but for admins only to update information of other
|
||||
object types such as lockers, enabling user accounts after being
|
||||
disbaled, etc.
|
||||
*/
|
||||
|
||||
func UpdateLockerCombo(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check locker number is included
|
||||
if data["lockernumber"] == "" || data["newlockercombo"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"lockercombo": data["newlockercombo"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := LockerCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"lockernumber": data["lockernumber"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the locker could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated locker",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateAdminName(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
cookie := c.Cookies("jwt")
|
||||
|
||||
token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(SecretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "not authorized",
|
||||
})
|
||||
}
|
||||
|
||||
claims := token.Claims.(*jwt.StandardClaims)
|
||||
|
||||
var admin models.Admin
|
||||
findErr := AdminCollection.FindOne(ctx, bson.M{"aid": claims.Issuer}).Decode(&admin)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "admin not found",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["firstname"] == "" || data["lastname"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"firstname": data["firstname"],
|
||||
"lastname": data["lastname"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"aid": claims.Issuer},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the admin could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated admin",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateAdminEmail(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
cookie := c.Cookies("jwt")
|
||||
|
||||
token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(SecretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "not authorized",
|
||||
})
|
||||
}
|
||||
|
||||
claims := token.Claims.(*jwt.StandardClaims)
|
||||
|
||||
var admin models.Admin
|
||||
findErr := AdminCollection.FindOne(ctx, bson.M{"aid": claims.Issuer}).Decode(&admin)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "admin not found",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["email"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"email": data["email"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"aid": claims.Issuer},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the admin could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated admin",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateAdminPassword(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
cookie := c.Cookies("jwt")
|
||||
|
||||
token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(SecretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "not authorized",
|
||||
})
|
||||
}
|
||||
|
||||
claims := token.Claims.(*jwt.StandardClaims)
|
||||
|
||||
var admin models.Admin
|
||||
findErr := AdminCollection.FindOne(ctx, bson.M{"aid": claims.Issuer}).Decode(&admin)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "admin not found",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["password"] == "" || data["newpassword1"] == "" || data["newpassword2"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
if !admin.ComparePasswords(data["password"]) {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your password is incorrect",
|
||||
})
|
||||
}
|
||||
|
||||
if data["newpassword1"] != data["newpassword2"] {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your new passwords must match",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"password": admin.HashPassword(data["newpassword1"]),
|
||||
"temppassword": false, // If it were a temp password, its not now
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"aid": claims.Issuer},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the admin password could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
subject := "Password Changed"
|
||||
receiver := admin.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/selfPasswordChanged.html", map[string]string{"username": admin.FirstName}); !sent {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Could not send password to admins email",
|
||||
})
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated admin password",
|
||||
})
|
||||
}
|
||||
|
||||
func RemoveStudentsDisabled(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authorized admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"account.accountdisabled": false,
|
||||
"account.alerted": false,
|
||||
"account.attempts": 0,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student account could not be enabled",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully enabled student account",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func RemoveTeachersDisabled(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authorized admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"account.accountdisabled": false,
|
||||
"account.attempts": 0,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.tid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher account could not be enabled",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully enabled teacher account",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
. "github.com/SowinskiBraeden/school-management-api/controllers"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
)
|
||||
|
||||
func UpdateContactName(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["_id"] == "" || data["firstname"] == "" || data["lastname"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var middlename string = ""
|
||||
|
||||
if data["middlename"] != "" {
|
||||
middlename = data["middlename"]
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"firstname": data["firstname"],
|
||||
"middlename": middlename,
|
||||
"lastname": data["lastname"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := ContactCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": data["_id"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the contact could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated contact",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateContactAddress(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["_id"] == "" || data["address"] == "" || data["city"] == "" || data["province"] == "" || data["postal"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"address": data["address"],
|
||||
"city": data["city"],
|
||||
"province": data["province"],
|
||||
"postal": data["postal"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := ContactCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": data["_id"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the contact could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated contact",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateContactHomePhone(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id of contact and new priority number is included
|
||||
if data["_id"] == "" || data["newnumber"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"homephone": data["newnumber"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := ContactCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": data["_id"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "contact could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated contact",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateContactWorkPhone(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id of contact and new priority number is included
|
||||
if data["_id"] == "" || data["newnumber"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"workphone": data["newnumber"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := ContactCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": data["_id"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "contact could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated contact",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateContactEmail(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id of contact and new priority number is included
|
||||
if data["_id"] == "" || data["email"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"email": data["email"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := ContactCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": data["_id"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "contact could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated contact",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateContactPriority(c *fiber.Ctx) error {
|
||||
var data map[string]interface{}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id of contact and new priority number is included
|
||||
if data["_id"] == nil || data["priority"] == nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var priority int = data["priority"].(int)
|
||||
|
||||
if priority > 10 || priority < 1 {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "invalid priority",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"priority": priority,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := ContactCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": data["_id"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "contact could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated contact",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,979 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
. "github.com/SowinskiBraeden/school-management-api/controllers"
|
||||
"github.com/SowinskiBraeden/school-management-api/models"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"github.com/google/uuid"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
)
|
||||
|
||||
func toBase64(b []byte) string {
|
||||
return base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
func UpdateStudentName(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id and names are included
|
||||
// Middle name is optional
|
||||
if data["uid"] == "" || data["firstname"] == "" || data["lastname"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var updateMiddle bool = false
|
||||
if data["middlename"] != "" {
|
||||
updateMiddle = true
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
var update bson.M
|
||||
if updateMiddle {
|
||||
update = bson.M{
|
||||
"$set": bson.M{
|
||||
"personal.firstname": data["firstname"],
|
||||
"personal.middlename": data["middlename"],
|
||||
"personal.lastname": data["lastname"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
} else {
|
||||
update = bson.M{
|
||||
"$set": bson.M{
|
||||
"personal.firstname": data["firstname"],
|
||||
"personal.lastname": data["lastname"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateStudentGradeLevel(c *fiber.Ctx) error {
|
||||
var data map[string]interface{}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authorized admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == nil || data["gradelevel"] == nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"school.gradelevel": data["gradelevel"].(float64),
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"].(string)},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student",
|
||||
})
|
||||
}
|
||||
|
||||
/*
|
||||
Far later on this function is going to be completely automated.
|
||||
Instead of an admin sending a request to update the homeroom of
|
||||
a student or teacher, the system will take the room number of
|
||||
the teacher's or student's Block 2 class from their schedule.
|
||||
|
||||
Though this function would remain for students only, for example
|
||||
a student requests a course change, if its their block 2 the
|
||||
admin would have to alter their homeroom to be the new class
|
||||
number.
|
||||
*/
|
||||
func UpdateStudentHomeroom(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == "" || data["homeroom"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"school.homeroom": data["homeroom"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateStudentPassword(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
cookie := c.Cookies("jwt")
|
||||
|
||||
token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(SecretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "not authorized",
|
||||
})
|
||||
}
|
||||
|
||||
claims := token.Claims.(*jwt.StandardClaims)
|
||||
|
||||
var student models.Student
|
||||
findErr := StudentCollection.FindOne(ctx, bson.M{"school.sid": claims.Issuer}).Decode(&student)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "student not found",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["password"] == "" || data["newpassword1"] == "" || data["newpassword2"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
if !student.ComparePasswords(data["password"]) {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your password is incorrect",
|
||||
})
|
||||
}
|
||||
|
||||
if data["newpassword1"] != data["newpassword2"] {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your new password must match",
|
||||
})
|
||||
}
|
||||
|
||||
if student.UsedPassword(data["newpassword1"]) {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your new password cannot be the same as a previous password",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"account.password": student.HashPassword(data["newpassword1"]),
|
||||
"account.temppassword": false, // If it were a temp password, its not now
|
||||
"updated_at": update_time,
|
||||
},
|
||||
"$push": bson.M{
|
||||
"account.hashhistory": student.HashPassword(data["newpassword1"]),
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": claims.Issuer},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student password could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
// Alert email the password has changed
|
||||
subject := "Password Changed"
|
||||
receiver := student.Personal.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/selfPasswordChanged.html", map[string]string{"username": student.Personal.FirstName}); !sent {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "failed to send email to student",
|
||||
})
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student password",
|
||||
})
|
||||
}
|
||||
|
||||
// This is for students to reset their password if they are unable to login
|
||||
func ResetStudentPassword(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included (email must be personal email)
|
||||
if data["uid"] == "" || data["email"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var student models.Student
|
||||
findErr := StudentCollection.FindOne(context.TODO(), bson.M{"school.sid": data["uid"]}).Decode(&student)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "student not found",
|
||||
})
|
||||
}
|
||||
|
||||
if student.Personal.Email != data["email"] {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your personal email is incorrect",
|
||||
})
|
||||
}
|
||||
|
||||
tempPass := student.GeneratePassword(12, 1, 1, 1)
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"account.password": student.HashPassword(tempPass),
|
||||
"account.temppassword": true,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student password could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
// Send student personal email temp password
|
||||
subject := "Password Changed"
|
||||
receiver := student.Personal.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/passwordChanged.html", map[string]string{"username": student.Personal.FirstName, "password": tempPass}); !sent {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Could not send password to students email",
|
||||
})
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student password",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateStudentLocker(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id and locker are included
|
||||
if data["uid"] == "" || data["lockernumber"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var locker models.Locker
|
||||
err := LockerCollection.FindOne(ctx, bson.M{"lockernumber": data["lockernumber"]}).Decode(&locker)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "locker not found",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"school.locker": locker.ID,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateStudentAddress(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == "" || data["address"] == "" || data["city"] == "" || data["province"] == "" || data["postal"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"personal.address": data["address"],
|
||||
"personal.city": data["city"],
|
||||
"personal.province": data["province"],
|
||||
"personal.postal": data["postal"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student",
|
||||
})
|
||||
}
|
||||
|
||||
// In the case a student gets held back a grade, we need to update their YOG (Year of Graduation)
|
||||
func UpdateStudentYOG(c *fiber.Ctx) error {
|
||||
var data map[string]interface{}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == "" || data["yog"] == nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var student models.Student
|
||||
findErr := StudentCollection.FindOne(context.TODO(), bson.M{"school.sid": data["uid"].(string)}).Decode(&student)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "student not found",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"school.yog": data["yog"].(int),
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"].(string)},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func RemoveStudentContact(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id and contact id are included
|
||||
if data["uid"] == "" || data["contactid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var contact models.Contact
|
||||
err := ContactCollection.FindOne(ctx, bson.M{"_id": data["contactid"]}).Decode(&contact)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "contact not found",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"updated_at": update_time,
|
||||
},
|
||||
"$pull": bson.M{
|
||||
"personal.contacts": contact.ID,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the contact could not be added",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully added contact",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func AddStudentContact(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id and contact id are included
|
||||
if data["uid"] == "" || data["contactid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var contact models.Contact
|
||||
err := ContactCollection.FindOne(ctx, bson.M{"_id": data["contactid"]}).Decode(&contact)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "contact not found",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"updated_at": update_time,
|
||||
},
|
||||
"$push": bson.M{
|
||||
"personal.contacts": contact.ID,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the contact could not be added",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully added contact",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateStudentPhoto(c *fiber.Ctx) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
//Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
sid := c.FormValue("sid")
|
||||
if sid == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
// Get student
|
||||
var student models.Student
|
||||
findErr := StudentCollection.FindOne(context.TODO(), bson.M{"school.sid": sid}).Decode(&student)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be found",
|
||||
"error": findErr,
|
||||
})
|
||||
}
|
||||
|
||||
// Collect image
|
||||
file, err := c.FormFile("image")
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be retrieved",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Get student photo
|
||||
var photo models.Photo
|
||||
findErr = ImageCollection.FindOne(context.TODO(), bson.M{"name": student.School.PhotoName}).Decode(&photo)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student image could not be found",
|
||||
"error": findErr,
|
||||
})
|
||||
}
|
||||
|
||||
// Save image to local
|
||||
uniqueId := uuid.New()
|
||||
filename := strings.Replace(uniqueId.String(), "-", "", -1)
|
||||
fileExt := strings.Split(file.Filename, ".")[1]
|
||||
image := fmt.Sprintf("%s.%s", filename, fileExt)
|
||||
err = c.SaveFile(file, fmt.Sprintf("./database/images/%s", image))
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be saved",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Read the entire file into a byte slice
|
||||
bytes, err := os.ReadFile(fmt.Sprintf("./database/images/%s", image))
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be read",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
var base64Encoding string = toBase64(bytes)
|
||||
|
||||
// Update image name and base64 data
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"base64": base64Encoding,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
_, updateErr := ImageCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": photo.ID},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
// Remove local image
|
||||
os.Remove(fmt.Sprintf("./database/images/%s", image))
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student photo",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateStudentEmail(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
var sid string
|
||||
var verifiedStudent bool
|
||||
verifiedAdmin, _ := AuthenticateUser(c, 3)
|
||||
verifiedStudent, sid = AuthenticateUser(c, 1)
|
||||
// Ensure Authenticated admin sent request
|
||||
if !verifiedAdmin && !verifiedStudent {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin or teacher can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
if verifiedAdmin && data["uid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
} else if verifiedAdmin {
|
||||
sid = data["uid"]
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["email"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"personal.email": data["email"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": sid},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,621 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
. "github.com/SowinskiBraeden/school-management-api/controllers"
|
||||
|
||||
"github.com/SowinskiBraeden/school-management-api/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"github.com/google/uuid"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
)
|
||||
|
||||
/*
|
||||
Far later on this function is going to be completely automated.
|
||||
Instead of an admin sending a request to update the homeroom of
|
||||
a student or teacher, the system will take the room number of
|
||||
the teacher's or student's Block 2 class from their schedule.
|
||||
|
||||
Though this function would remain for students only, for example
|
||||
a student requests a course change, if its their block 2 the
|
||||
admin would have to alter their homeroom to be the new class
|
||||
number.
|
||||
*/
|
||||
func UpdateTeacherHomeroom(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == "" || data["homeroom"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"school.homeroom": data["homeroom"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.tid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated teacher",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateTeacherPassword(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
cookie := c.Cookies("jwt")
|
||||
|
||||
token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(SecretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "not authorized",
|
||||
})
|
||||
}
|
||||
|
||||
claims := token.Claims.(*jwt.StandardClaims)
|
||||
|
||||
var teacher models.Teacher
|
||||
findErr := TeacherCollection.FindOne(ctx, bson.M{"school.tid": claims.Issuer}).Decode(&teacher)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "teacher not found",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["password"] == "" || data["newpassword1"] == "" || data["newpassword2"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
if !teacher.ComparePasswords(data["password"]) {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your password is incorrect",
|
||||
})
|
||||
}
|
||||
|
||||
if data["newpassword1"] != data["newpassword2"] {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your new passwords must match",
|
||||
})
|
||||
}
|
||||
|
||||
if teacher.UsedPassword(data["newpassword1"]) {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your new password cannot be the same as a previous password",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"account.password": teacher.HashPassword(data["newpassword1"]),
|
||||
"account.temppassword": false, // If it were a temp password, its not now
|
||||
"updated_at": update_time,
|
||||
},
|
||||
"$push": bson.M{
|
||||
"account.hashhistory": teacher.HashPassword(data["newpassword1"]),
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.tid": claims.Issuer},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher password could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
subject := "Password Changed"
|
||||
receiver := teacher.Personal.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/selfPasswordChanged.html", map[string]string{"username": teacher.Personal.FirstName}); !sent {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Could not send password to teachers email",
|
||||
})
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated teacher password",
|
||||
})
|
||||
}
|
||||
|
||||
func ResetTeacherPassword(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included (email must be personal email)
|
||||
if data["uid"] == "" || data["email"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var teacher models.Teacher
|
||||
findErr := TeacherCollection.FindOne(context.TODO(), bson.M{"school.tid": data["uid"]}).Decode(&teacher)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "teacher not found",
|
||||
})
|
||||
}
|
||||
|
||||
if teacher.Personal.Email != data["email"] {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your personal email is incorrect",
|
||||
})
|
||||
}
|
||||
|
||||
tempPass := teacher.GeneratePassword(12, 1, 1, 1)
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"account.password": teacher.HashPassword(tempPass),
|
||||
"account.temppassword": true,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.tid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher password could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
// Send teacher personal email temp password
|
||||
subject := "Password Changed"
|
||||
receiver := teacher.Personal.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/passwordChanged.html", map[string]string{"username": teacher.Personal.FirstName, "password": tempPass}); !sent {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Could not send password to teachers email",
|
||||
})
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated teacher password",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateTeacherAddress(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == "" || data["address"] == "" || data["city"] == "" || data["province"] == "" || data["postal"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"personal.address": data["address"],
|
||||
"personal.city": data["city"],
|
||||
"personal.province": data["province"],
|
||||
"personal.postal": data["postal"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.tid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated teacher",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateTeacherPhoto(c *fiber.Ctx) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
//Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
tid := c.FormValue("tid")
|
||||
if tid == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
// Get teacher
|
||||
var teacher models.Teacher
|
||||
findErr := TeacherCollection.FindOne(context.TODO(), bson.M{"school.tid": tid}).Decode(&teacher)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher could not be found",
|
||||
"error": findErr,
|
||||
})
|
||||
}
|
||||
|
||||
// Collect image
|
||||
file, err := c.FormFile("image")
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be retrieved",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Get student photo
|
||||
var photo models.Photo
|
||||
findErr = ImageCollection.FindOne(context.TODO(), bson.M{"name": teacher.School.PhotoName}).Decode(&photo)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student image could not be found",
|
||||
"error": findErr,
|
||||
})
|
||||
}
|
||||
|
||||
// Save image to local
|
||||
uniqueId := uuid.New()
|
||||
filename := strings.Replace(uniqueId.String(), "-", "", -1)
|
||||
fileExt := strings.Split(file.Filename, ".")[1]
|
||||
image := fmt.Sprintf("%s.%s", filename, fileExt)
|
||||
err = c.SaveFile(file, fmt.Sprintf("./database/images/%s", image))
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be saved",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Read the entire file into a byte slice
|
||||
bytes, err := os.ReadFile(fmt.Sprintf("./database/images/%s", image))
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be read",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
var base64Encoding string = toBase64(bytes)
|
||||
|
||||
// Update image name and base64 data
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"base64": base64Encoding,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
_, updateErr := ImageCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": photo.ID},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
// Remove local image
|
||||
os.Remove(fmt.Sprintf("./database/images/%s", image))
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated teacher photo",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateTeacherEmail(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
var tid string
|
||||
var verifiedTeacher bool
|
||||
|
||||
verifiedAdmin, _ := AuthenticateUser(c, 3)
|
||||
verifiedTeacher, tid = AuthenticateUser(c, 2)
|
||||
// Ensure Authenticated admin sent request
|
||||
if !verifiedAdmin && !verifiedTeacher {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin or teacher can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
if verifiedAdmin && data["uid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
} else if verifiedAdmin {
|
||||
tid = data["uid"]
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["email"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"personal.email": data["email"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.tid": tid},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated teacher",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateTeacherName(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id and names are included
|
||||
if data["uid"] == "" || data["firstname"] == "" || data["lastname"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
// Get teacher
|
||||
var teacher models.Teacher
|
||||
findErr := TeacherCollection.FindOne(ctx, bson.M{"school.tid": data["uid"]}).Decode(&teacher)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher could not be found",
|
||||
"error": findErr,
|
||||
})
|
||||
}
|
||||
|
||||
var middlename string = ""
|
||||
|
||||
if data["middlename"] != "" {
|
||||
middlename = data["middlename"]
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"personal.firstname": data["firstname"],
|
||||
"personal.middlename": middlename,
|
||||
"personal.lastname": data["lastname"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.tid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated teacher",
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,19 +1,34 @@
|
||||
module github.com/SowinskiBraeden/school-management-api
|
||||
|
||||
go 1.16
|
||||
go 1.19
|
||||
|
||||
require (
|
||||
github.com/gofiber/fiber/v2 v2.26.0
|
||||
github.com/golang-jwt/jwt v3.2.1+incompatible
|
||||
github.com/google/go-cmp v0.5.6 // indirect
|
||||
github.com/gofiber/fiber/v2 v2.36.0
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/howeyc/gopass v0.0.0-20210920133722-c8aef6fb66ef
|
||||
github.com/joho/godotenv v1.3.0
|
||||
github.com/stretchr/testify v1.7.0 // indirect
|
||||
github.com/valyala/fasthttp v1.34.0 // indirect
|
||||
go.mongodb.org/mongo-driver v1.7.2
|
||||
golang.org/x/crypto v0.0.0-20220214200702-86341886e292
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
|
||||
github.com/joho/godotenv v1.4.0
|
||||
go.mongodb.org/mongo-driver v1.10.1
|
||||
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/andybalholm/brotli v1.0.4 // indirect
|
||||
github.com/golang/snappy v0.0.4 // indirect
|
||||
github.com/google/go-cmp v0.5.8 // indirect
|
||||
github.com/klauspost/compress v1.15.9 // indirect
|
||||
github.com/montanaflynn/stats v0.6.6 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/stretchr/testify v1.8.0 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasthttp v1.38.0 // indirect
|
||||
github.com/valyala/tcplisten v1.0.0 // indirect
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
|
||||
github.com/xdg-go/scram v1.1.1 // indirect
|
||||
github.com/xdg-go/stringprep v1.0.3 // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a // indirect
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab // indirect
|
||||
golang.org/x/term v0.0.0-20220722155259-a9ba230a4035 // indirect
|
||||
golang.org/x/text v0.3.7 // indirect
|
||||
)
|
||||
@@ -1,162 +1,96 @@
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/andybalholm/brotli v1.0.2/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y=
|
||||
github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY=
|
||||
github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
|
||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||
github.com/gobuffalo/attrs v0.0.0-20190224210810-a9411de4debd/go.mod h1:4duuawTqi2wkkpB4ePgWMaai6/Kc6WEz83bhFwpHzj0=
|
||||
github.com/gobuffalo/depgen v0.0.0-20190329151759-d478694a28d3/go.mod h1:3STtPUQYuzV0gBVOY3vy6CfMm/ljR4pABfrTeHNLHUY=
|
||||
github.com/gobuffalo/depgen v0.1.0/go.mod h1:+ifsuy7fhi15RWncXQQKjWS9JPkdah5sZvtHc2RXGlg=
|
||||
github.com/gobuffalo/envy v1.6.15/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI=
|
||||
github.com/gobuffalo/envy v1.7.0/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI=
|
||||
github.com/gobuffalo/flect v0.1.0/go.mod h1:d2ehjJqGOH/Kjqcoz+F7jHTBbmDb38yXA598Hb50EGs=
|
||||
github.com/gobuffalo/flect v0.1.1/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI=
|
||||
github.com/gobuffalo/flect v0.1.3/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI=
|
||||
github.com/gobuffalo/genny v0.0.0-20190329151137-27723ad26ef9/go.mod h1:rWs4Z12d1Zbf19rlsn0nurr75KqhYp52EAGGxTbBhNk=
|
||||
github.com/gobuffalo/genny v0.0.0-20190403191548-3ca520ef0d9e/go.mod h1:80lIj3kVJWwOrXWWMRzzdhW3DsrdjILVil/SFKBzF28=
|
||||
github.com/gobuffalo/genny v0.1.0/go.mod h1:XidbUqzak3lHdS//TPu2OgiFB+51Ur5f7CSnXZ/JDvo=
|
||||
github.com/gobuffalo/genny v0.1.1/go.mod h1:5TExbEyY48pfunL4QSXxlDOmdsD44RRq4mVZ0Ex28Xk=
|
||||
github.com/gobuffalo/gitgen v0.0.0-20190315122116-cc086187d211/go.mod h1:vEHJk/E9DmhejeLeNt7UVvlSGv3ziL+djtTr3yyzcOw=
|
||||
github.com/gobuffalo/gogen v0.0.0-20190315121717-8f38393713f5/go.mod h1:V9QVDIxsgKNZs6L2IYiGR8datgMhB577vzTDqypH360=
|
||||
github.com/gobuffalo/gogen v0.1.0/go.mod h1:8NTelM5qd8RZ15VjQTFkAW6qOMx5wBbW4dSCS3BY8gg=
|
||||
github.com/gobuffalo/gogen v0.1.1/go.mod h1:y8iBtmHmGc4qa3urIyo1shvOD8JftTtfcKi+71xfDNE=
|
||||
github.com/gobuffalo/logger v0.0.0-20190315122211-86e12af44bc2/go.mod h1:QdxcLw541hSGtBnhUc4gaNIXRjiDppFGaDqzbrBd3v8=
|
||||
github.com/gobuffalo/mapi v1.0.1/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc=
|
||||
github.com/gobuffalo/mapi v1.0.2/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc=
|
||||
github.com/gobuffalo/packd v0.0.0-20190315124812-a385830c7fc0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4=
|
||||
github.com/gobuffalo/packd v0.1.0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4=
|
||||
github.com/gobuffalo/packr/v2 v2.0.9/go.mod h1:emmyGweYTm6Kdper+iywB6YK5YzuKchGtJQZ0Odn4pQ=
|
||||
github.com/gobuffalo/packr/v2 v2.2.0/go.mod h1:CaAwI0GPIAv+5wKLtv8Afwl+Cm78K/I/VCm/3ptBN+0=
|
||||
github.com/gobuffalo/syncx v0.0.0-20190224160051-33c29581e754/go.mod h1:HhnNqWY95UYwwW3uSASeV7vtgYkT2t16hJgV3AEPUpw=
|
||||
github.com/gofiber/fiber/v2 v2.26.0 h1:Awnfqp3fqbZzV3wZWMRJ6Xo2U8X0Ls68M7tXjx52NcM=
|
||||
github.com/gofiber/fiber/v2 v2.26.0/go.mod h1:7efVWcBOZi1PyMWznnbitjnARPA7nYZxmQXJVod0bo0=
|
||||
github.com/golang-jwt/jwt v3.2.1+incompatible h1:73Z+4BJcrTC+KczS6WvTPvRGOp1WmfEP4Q1lOd9Z/+c=
|
||||
github.com/golang-jwt/jwt v3.2.1+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
|
||||
github.com/gofiber/fiber/v2 v2.36.0 h1:1qLMe5rhXFLPa2SjK10Wz7WFgLwYi4TYg7XrjztJHqA=
|
||||
github.com/gofiber/fiber/v2 v2.36.0/go.mod h1:tgCr+lierLwLoVHHO/jn3Niannv34WRkQETU8wiL9fQ=
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
|
||||
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/golang/snappy v0.0.3 h1:fHPg5GQYlCeLIPB9BZqMVR5nR9A+IM5zcgeTdjMYmLA=
|
||||
github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
|
||||
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ=
|
||||
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
|
||||
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/howeyc/gopass v0.0.0-20210920133722-c8aef6fb66ef h1:A9HsByNhogrvm9cWb28sjiS3i7tcKCkflWFEkHfuAgM=
|
||||
github.com/howeyc/gopass v0.0.0-20210920133722-c8aef6fb66ef/go.mod h1:lADxMC39cJJqL93Duh1xhAs4I2Zs8mKS89XWXFGp9cs=
|
||||
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
||||
github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc=
|
||||
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
|
||||
github.com/karrick/godirwalk v1.8.0/go.mod h1:H5KPZjojv4lE+QYImBI8xVtrBRgYrIVsaRPx4tDPEn4=
|
||||
github.com/karrick/godirwalk v1.10.3/go.mod h1:RoGL9dQei4vP9ilrpETWE8CLOZ1kiN0LhBygSwrAsHA=
|
||||
github.com/klauspost/compress v1.9.5/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
|
||||
github.com/klauspost/compress v1.13.4/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg=
|
||||
github.com/klauspost/compress v1.15.0 h1:xqfchp4whNFxn5A4XFyyYtitiWI8Hy5EW59jEwcyL6U=
|
||||
github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg=
|
||||
github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
||||
github.com/klauspost/compress v1.15.0/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/klauspost/compress v1.15.9 h1:wKRjX6JRtDdrE9qwa4b/Cip7ACOshUI4smpCQanqjSY=
|
||||
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/markbates/oncer v0.0.0-20181203154359-bf2de49a0be2/go.mod h1:Ld9puTsIW75CHf65OeIOkyKbteujpZVXDpWK6YGZbxE=
|
||||
github.com/markbates/safe v1.0.1/go.mod h1:nAqgmRi7cY2nqMc92/bSEeQA+R4OheNU2T1kNSCBdG0=
|
||||
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
|
||||
github.com/pelletier/go-toml v1.7.0/go.mod h1:vwGMzjaWMwyfHwgIBhI2YUM4fB6nL6lVAvS1LBMMhTE=
|
||||
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/montanaflynn/stats v0.6.6 h1:Duep6KMIDpY4Yo11iFsvyqJDyfzLF9+sndUKT+v64GQ=
|
||||
github.com/montanaflynn/stats v0.6.6/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
|
||||
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
|
||||
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4=
|
||||
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasthttp v1.32.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD3K/7o2Cus=
|
||||
github.com/valyala/fasthttp v1.34.0 h1:d3AAQJ2DRcxJYHm7OXNXtXt2as1vMDfxeIcFvhmGGm4=
|
||||
github.com/valyala/fasthttp v1.34.0/go.mod h1:epZA5N+7pY6ZaEKRmstzOuYJx9HI8DI1oaCGZpdH4h0=
|
||||
github.com/valyala/fasthttp v1.38.0 h1:yTjSSNjuDi2PPvXY2836bIwLmiTS2T4T9p1coQshpco=
|
||||
github.com/valyala/fasthttp v1.38.0/go.mod h1:t/G+3rLek+CyY9bnIE+YlMRddxVAAGjhxndDB4i4C0I=
|
||||
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
|
||||
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
|
||||
github.com/xdg-go/scram v1.0.2 h1:akYIkZ28e6A96dkWNJQu3nmCzH3YfwMPQExUYDaRv7w=
|
||||
github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs=
|
||||
github.com/xdg-go/stringprep v1.0.2 h1:6iq84/ryjjeRmMJwxutI51F2GIPlP5BfTvXHeYjyhBc=
|
||||
github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM=
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
|
||||
github.com/xdg-go/scram v1.1.1 h1:VOMT+81stJgXW3CpHyqHN3AXDYIMsx56mEFrB37Mb/E=
|
||||
github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g=
|
||||
github.com/xdg-go/stringprep v1.0.3 h1:kdwGpVNwPFtjs98xCGkHjQtGKh86rDcRZN17QEMCOIs=
|
||||
github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8=
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
|
||||
go.mongodb.org/mongo-driver v1.7.2 h1:pFttQyIiJUHEn50YfZgC9ECjITMT44oiN36uArf/OFg=
|
||||
go.mongodb.org/mongo-driver v1.7.2/go.mod h1:Q4oFMbo1+MSNqICAdYMlC/zSTrwCogR4R8NzkI+yfU8=
|
||||
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a h1:fZHgsYlfvtyqToslyjUt3VOPF4J7aK/3MPcK7xp3PDk=
|
||||
github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a/go.mod h1:ul22v+Nro/R083muKhosV54bj5niojjWZvU8xrevuH4=
|
||||
go.mongodb.org/mongo-driver v1.10.1 h1:NujsPveKwHaWuKUer/ceo9DzEe7HIj1SlJ6uvXZG0S4=
|
||||
go.mongodb.org/mongo-driver v1.10.1/go.mod h1:z4XpeoU6w+9Vht+jAFyLgVrD+jGSQQe0+CBWFHNiHt8=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190422162423-af44ce270edf/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE=
|
||||
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
|
||||
golang.org/x/crypto v0.0.0-20220214200702-86341886e292 h1:f+lwQ+GtmgoY+A2YaQxlSOnDjXcQ7ZRLWOHbC6HtRqE=
|
||||
golang.org/x/crypto v0.0.0-20220214200702-86341886e292/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa h1:zuSxTR4o9y82ebqCUJYNGJbGPo6sKVl54f/TVDObg1c=
|
||||
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
|
||||
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190412183630-56d357773e84/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 h1:uVc8UZUe6tr40fFVnUP5Oj+veunVezqYl9z7DYw9xzw=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190419153524-e8e3143a4f4a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190531175056-4c3a928424d2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9 h1:nhht2DYV/Sn3qOayu8lM+cU1ii9sTLUeBQwQQfUHtrs=
|
||||
golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab h1:2QkjZIsXupsJbJIdSjjUOgWK3aEtzyuh2mPt3l/CkeU=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.0.0-20220722155259-a9ba230a4035 h1:Q5284mrmYTpACcm+eAKjKJH48BBwSyfJqmmGDTtT8Vc=
|
||||
golang.org/x/term v0.0.0-20220722155259-a9ba230a4035/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190329151228-23e29df326fe/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190416151739-9c9e1878f421/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190420181800-aa740d480789/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"github.com/gofiber/fiber/v2/middleware/cors"
|
||||
)
|
||||
|
||||
const version string = "\nv1.0.0-Beta"
|
||||
const version string = "\nv1.1.3-Beta"
|
||||
|
||||
func main() {
|
||||
fmt.Println(version)
|
||||
|
||||
+29
-11
@@ -1,17 +1,24 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/SowinskiBraeden/school-management-api/database"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
var AdminCollection *mongo.Collection = database.OpenCollection(database.Client, "admins")
|
||||
|
||||
type Admin struct {
|
||||
ID primitive.ObjectID `bson:"_id"`
|
||||
FirstName string `json:"firstname" validate:"required"`
|
||||
@@ -25,10 +32,24 @@ type Admin struct {
|
||||
Updated_at time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (a *Admin) GenerateSchoolEmail() string {
|
||||
func (a *Admin) EmailExists(email string) bool {
|
||||
var admin Admin
|
||||
findErr := AdminCollection.FindOne(context.TODO(), bson.M{"account.schoolemail": email}).Decode(&admin)
|
||||
return findErr == nil
|
||||
}
|
||||
|
||||
func (a *Admin) GenerateSchoolEmail(offset int, lastEmail string) string {
|
||||
addr := os.Getenv("SYSTEM_EMAIL_ADDRESS")
|
||||
var email string = strings.ToLower(a.LastName) + "_" + strings.ToLower(string(a.FirstName[0])) + addr
|
||||
// Add check to see if email already exists
|
||||
if offset > 0 && offset < len([]rune(a.FirstName))-1 {
|
||||
email = lastEmail[:strings.Index(lastEmail, "_")+offset+1] + strings.ToLower(string(a.FirstName[offset])) + addr
|
||||
}
|
||||
if offset == len([]rune(a.FirstName))-1 {
|
||||
email = strings.ToLower(a.LastName) + "_" + strings.ToLower(a.FirstName) + addr
|
||||
}
|
||||
if offset > len([]rune(a.FirstName))-1 {
|
||||
email = strings.ToLower(a.LastName) + "_" + strings.ToLower(a.FirstName) + strconv.Itoa(offset-len([]rune(a.FirstName))) + addr
|
||||
}
|
||||
return email
|
||||
}
|
||||
|
||||
@@ -37,15 +58,12 @@ func (s *Admin) HashPassword(password string) string {
|
||||
return string(hash)
|
||||
}
|
||||
|
||||
func (s *Admin) ComparePasswords(password string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(s.Password), []byte(password))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
func (a *Admin) ComparePasswords(password string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(a.Password), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (s *Admin) CheckPasswordStrength(password string) bool {
|
||||
func (a *Admin) CheckPasswordStrength(password string) bool {
|
||||
|
||||
var hasUpper bool = false
|
||||
for _, r := range password {
|
||||
@@ -61,14 +79,14 @@ func (s *Admin) CheckPasswordStrength(password string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
if strings.ContainsAny(password, specialCharSet) && hasLower && hasUpper {
|
||||
if strings.ContainsAny(password, specialCharSet) && hasLower && hasUpper && len(password) >= 8 {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Admin) GeneratePassword(passwordLength, minSpecialChar, minNum, minUpperCase int) string {
|
||||
func (a *Admin) GeneratePassword(passwordLength, minSpecialChar, minNum, minUpperCase int) string {
|
||||
var password strings.Builder
|
||||
|
||||
//Set special character
|
||||
|
||||
+22
-27
@@ -18,12 +18,12 @@ import (
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
var lockerCollection *mongo.Collection = database.OpenCollection(database.Client, "lockers")
|
||||
var studentCollection *mongo.Collection = database.OpenCollection(database.Client, "students")
|
||||
var LockerCollection *mongo.Collection = database.OpenCollection(database.Client, "lockers")
|
||||
var StudentCollection *mongo.Collection = database.OpenCollection(database.Client, "students")
|
||||
|
||||
type Student struct {
|
||||
ID primitive.ObjectID `bson:"_id"`
|
||||
PersonalData struct {
|
||||
Personal struct {
|
||||
FirstName string `json:"firstname" validate:"required"`
|
||||
MiddleName string `json:"middlename"`
|
||||
LastName string `json:"lastname" validate:"required"`
|
||||
@@ -35,8 +35,8 @@ type Student struct {
|
||||
Postal string `json:"postal"`
|
||||
DOB string `json:"dob" validate:"required"`
|
||||
Contacts []string `json:"contacts"` // List of contact ID's rather than contact object
|
||||
} `json:"personaldata"`
|
||||
SchoolData struct {
|
||||
} `json:"personal"`
|
||||
School struct {
|
||||
GradeLevel float64 `json:"gradelevel" validate:"required"`
|
||||
SID string `json:"sid"` // Student ID
|
||||
PEN string `json:"ped"` // Personal Education Number
|
||||
@@ -44,8 +44,9 @@ type Student struct {
|
||||
Locker string `json:"-"` // Locker ID
|
||||
YOG int `json:"yog"` // Year of Graduation
|
||||
PhotoName string `json:"photoname"` // name of photo in db
|
||||
} `json:"schooldata"`
|
||||
AccountData struct {
|
||||
} `json:"School"`
|
||||
Account struct {
|
||||
VerifiedEmail bool `json:"verifiedemail"`
|
||||
SchoolEmail string `json:"schoolemail"`
|
||||
Password string `json:"-" validate:"min=10,max=32"`
|
||||
AccountDisabled bool `bson:"accountdisabled"`
|
||||
@@ -53,13 +54,13 @@ type Student struct {
|
||||
TempPassword bool `json:"temppassword"`
|
||||
Attempts int `json:"attempts"` // login attempts max 5
|
||||
HashHistory []string `json:"-"` // List of old hashed passwords (not including auto generated passwords)
|
||||
} `json:"accountdata"`
|
||||
} `json:"Account"`
|
||||
Created_at time.Time `json:"created_at"`
|
||||
Updated_at time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (s *Student) UsedPassword(password string) bool {
|
||||
for _, oldHash := range s.AccountData.HashHistory {
|
||||
for _, oldHash := range s.Account.HashHistory {
|
||||
if oldHash == s.HashPassword(password) {
|
||||
return true
|
||||
}
|
||||
@@ -74,34 +75,28 @@ func (s *Student) HashPassword(password string) string {
|
||||
|
||||
func (s *Student) EmailExists(email string) bool {
|
||||
var student Student
|
||||
findErr := studentCollection.FindOne(context.TODO(), bson.M{"accountdata.schoolemail": email}).Decode(&student)
|
||||
if findErr != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
findErr := StudentCollection.FindOne(context.TODO(), bson.M{"account.schoolemail": email}).Decode(&student)
|
||||
return findErr == nil
|
||||
}
|
||||
|
||||
func (s *Student) GenerateSchoolEmail(offset int, lastEmail string) string {
|
||||
addr := os.Getenv("SYSTEM_EMAIL_ADDRESS")
|
||||
var email string = strings.ToLower(string(s.PersonalData.FirstName[0])) + "." + strings.ToLower(s.PersonalData.LastName) + addr
|
||||
if offset > 0 && offset < len([]rune(s.PersonalData.FirstName))-1 {
|
||||
email = lastEmail[:offset] + strings.ToLower(string(s.PersonalData.FirstName[offset])) + lastEmail[offset:] + addr
|
||||
var email string = strings.ToLower(string(s.Personal.FirstName[0])) + "." + strings.ToLower(s.Personal.LastName) + addr
|
||||
if offset > 0 && offset < len([]rune(s.Personal.FirstName))-1 {
|
||||
email = lastEmail[:offset] + strings.ToLower(string(s.Personal.FirstName[offset])) + lastEmail[offset:] + addr
|
||||
}
|
||||
if offset == len([]rune(s.PersonalData.FirstName))-1 {
|
||||
email = strings.ToLower(s.PersonalData.FirstName) + "." + strings.ToLower(s.PersonalData.LastName) + addr
|
||||
if offset == len([]rune(s.Personal.FirstName))-1 {
|
||||
email = strings.ToLower(s.Personal.FirstName) + "." + strings.ToLower(s.Personal.LastName) + addr
|
||||
}
|
||||
if offset > len([]rune(s.PersonalData.FirstName))-1 {
|
||||
email = strings.ToLower(s.PersonalData.FirstName) + "." + strings.ToLower(s.PersonalData.LastName) + strconv.Itoa(offset-len([]rune(s.PersonalData.FirstName))) + addr
|
||||
if offset > len([]rune(s.Personal.FirstName))-1 {
|
||||
email = strings.ToLower(s.Personal.FirstName) + "." + strings.ToLower(s.Personal.LastName) + strconv.Itoa(offset-len([]rune(s.Personal.FirstName))) + addr
|
||||
}
|
||||
return email
|
||||
}
|
||||
|
||||
func (s *Student) ComparePasswords(password string) bool { //True: passwords match, False: no match
|
||||
valid := bcrypt.CompareHashAndPassword([]byte(s.AccountData.Password), []byte(password))
|
||||
if valid != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
valid := bcrypt.CompareHashAndPassword([]byte(s.Account.Password), []byte(password))
|
||||
return valid == nil
|
||||
}
|
||||
|
||||
func (s *Student) CheckPasswordStrength(password string) bool {
|
||||
@@ -120,7 +115,7 @@ func (s *Student) CheckPasswordStrength(password string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
if strings.ContainsAny(password, specialCharSet) && hasLower && hasUpper {
|
||||
if strings.ContainsAny(password, specialCharSet) && hasLower && hasUpper && len(password) >= 8 {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
|
||||
+21
-26
@@ -24,11 +24,11 @@ var (
|
||||
allCharSet = lowerCharSet + upperCharSet + specialCharSet + numberSet
|
||||
)
|
||||
|
||||
var teacherCollection *mongo.Collection = database.OpenCollection(database.Client, "teachers")
|
||||
var TeacherCollection *mongo.Collection = database.OpenCollection(database.Client, "teachers")
|
||||
|
||||
type Teacher struct {
|
||||
ID primitive.ObjectID `bson:"_id"`
|
||||
PersonalData struct {
|
||||
Personal struct {
|
||||
FirstName string `json:"firstname" validate:"required"`
|
||||
MiddleName string `json:"middlename"`
|
||||
LastName string `json:"lastname" validate:"required"`
|
||||
@@ -38,26 +38,27 @@ type Teacher struct {
|
||||
Province string `json:"province"`
|
||||
Postal string `json:"postal"`
|
||||
DOB string `json:"dob" validate:"required"`
|
||||
} `json:"personaldata"`
|
||||
SchoolData struct {
|
||||
} `json:"personal"`
|
||||
School struct {
|
||||
TID string `json:"tid"` // Teacher ID
|
||||
Homeroom string `json:"homeroom"`
|
||||
PhotoName string `json:"photoname"` // name of photo in db
|
||||
} `json:"schooldata"`
|
||||
AccountData struct {
|
||||
} `json:"School"`
|
||||
Account struct {
|
||||
VerifiedEmail bool `json:"verifiedemail"`
|
||||
SchoolEmail string `json:"schoolemail"`
|
||||
Password string `json:"-" validate:"min=10,max=32"`
|
||||
AccountDisabled bool `bson:"accountdisabled"`
|
||||
TempPassword bool `json:"temppassword"`
|
||||
Attempts int `json:"attempts"` // login attempts max 5
|
||||
HashHistory []string `json:"-"` // List of old hashed passwords (not including auto generated passwords)
|
||||
} `json:"accountdata"`
|
||||
} `json:"Account"`
|
||||
Created_at time.Time `json:"created_at"`
|
||||
Updated_at time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (t *Teacher) UsedPassword(password string) bool {
|
||||
for _, oldHash := range t.AccountData.HashHistory {
|
||||
for _, oldHash := range t.Account.HashHistory {
|
||||
if oldHash == t.HashPassword(password) {
|
||||
return true
|
||||
}
|
||||
@@ -72,34 +73,28 @@ func (t *Teacher) HashPassword(password string) string {
|
||||
|
||||
func (t *Teacher) EmailExists(email string) bool {
|
||||
var teacher Teacher
|
||||
findErr := teacherCollection.FindOne(context.TODO(), bson.M{"accountdata.schoolemail": email}).Decode(&teacher)
|
||||
if findErr != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
findErr := TeacherCollection.FindOne(context.TODO(), bson.M{"account.schoolemail": email}).Decode(&teacher)
|
||||
return findErr == nil
|
||||
}
|
||||
|
||||
func (t *Teacher) GenerateSchoolEmail(offset int, lastEmail string) string {
|
||||
addr := os.Getenv("SYSTEM_EMAIL_ADDRESS")
|
||||
var email string = strings.ToLower(t.PersonalData.LastName) + "_" + strings.ToLower(string(t.PersonalData.FirstName[0])) + addr
|
||||
if offset > 0 && offset < len([]rune(t.PersonalData.FirstName))-1 {
|
||||
email = lastEmail[:strings.Index(lastEmail, "_")+offset+1] + strings.ToLower(string(t.PersonalData.FirstName[offset])) + addr
|
||||
var email string = strings.ToLower(t.Personal.LastName) + "_" + strings.ToLower(string(t.Personal.FirstName[0])) + addr
|
||||
if offset > 0 && offset < len([]rune(t.Personal.FirstName))-1 {
|
||||
email = lastEmail[:strings.Index(lastEmail, "_")+offset+1] + strings.ToLower(string(t.Personal.FirstName[offset])) + addr
|
||||
}
|
||||
if offset == len([]rune(t.PersonalData.FirstName))-1 {
|
||||
email = strings.ToLower(t.PersonalData.LastName) + "_" + strings.ToLower(t.PersonalData.FirstName) + addr
|
||||
if offset == len([]rune(t.Personal.FirstName))-1 {
|
||||
email = strings.ToLower(t.Personal.LastName) + "_" + strings.ToLower(t.Personal.FirstName) + addr
|
||||
}
|
||||
if offset > len([]rune(t.PersonalData.FirstName))-1 {
|
||||
email = strings.ToLower(t.PersonalData.LastName) + "_" + strings.ToLower(t.PersonalData.FirstName) + strconv.Itoa(offset-len([]rune(t.PersonalData.FirstName))) + addr
|
||||
if offset > len([]rune(t.Personal.FirstName))-1 {
|
||||
email = strings.ToLower(t.Personal.LastName) + "_" + strings.ToLower(t.Personal.FirstName) + strconv.Itoa(offset-len([]rune(t.Personal.FirstName))) + addr
|
||||
}
|
||||
return email
|
||||
}
|
||||
|
||||
func (t *Teacher) ComparePasswords(password string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(t.AccountData.Password), []byte(password))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
err := bcrypt.CompareHashAndPassword([]byte(t.Account.Password), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (t *Teacher) CheckPasswordStrength(password string) bool {
|
||||
@@ -118,7 +113,7 @@ func (t *Teacher) CheckPasswordStrength(password string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
if strings.ContainsAny(password, specialCharSet) && hasLower && hasUpper {
|
||||
if strings.ContainsAny(password, specialCharSet) && hasLower && hasUpper && len(password) >= 8 {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
|
||||
+34
-33
@@ -2,6 +2,7 @@ package routes
|
||||
|
||||
import (
|
||||
"github.com/SowinskiBraeden/school-management-api/controllers"
|
||||
"github.com/SowinskiBraeden/school-management-api/controllers/update"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
@@ -27,28 +28,28 @@ func Setup(app *fiber.App) {
|
||||
app.Post(routerPrefix+"/student/login", controllers.StudentLogin)
|
||||
|
||||
// Update Student Handler
|
||||
app.Post(routerPrefix+"/student/updateName", controllers.UpdateStudentName)
|
||||
app.Post(routerPrefix+"/student/updateGradeLevel", controllers.UpdateStudentGradeLevel)
|
||||
app.Post(routerPrefix+"/student/updateHomeroom", controllers.UpdateStudentHomeroom)
|
||||
app.Post(routerPrefix+"/student/updateLocker", controllers.UpdateStudentLocker)
|
||||
app.Post(routerPrefix+"/studnet/updateYOG", controllers.UpdateStudentYOG)
|
||||
app.Post(routerPrefix+"/studnet/addContact", controllers.AddStudentContact)
|
||||
app.Post(routerPrefix+"/student/removeContact", controllers.RemoveStudentContact)
|
||||
app.Post(routerPrefix+"/student/updatePassword", controllers.UpdateStudentPassword)
|
||||
app.Post(routerPrefix+"/student/resetPassword", controllers.ResetStudentPassword)
|
||||
app.Post(routerPrefix+"/student/updateAddress", controllers.UpdateStudentAddress)
|
||||
app.Post(routerPrefix+"/student/updatePhoto", controllers.UpdateStudentPhoto)
|
||||
app.Post(routerPrefix+"/student/updateEmail", controllers.UpdateStudentEmail)
|
||||
app.Post(routerPrefix+"/student/updateName", update.UpdateStudentName)
|
||||
app.Post(routerPrefix+"/student/updateGradeLevel", update.UpdateStudentGradeLevel)
|
||||
app.Post(routerPrefix+"/student/updateHomeroom", update.UpdateStudentHomeroom)
|
||||
app.Post(routerPrefix+"/student/updateLocker", update.UpdateStudentLocker)
|
||||
app.Post(routerPrefix+"/studnet/updateYOG", update.UpdateStudentYOG)
|
||||
app.Post(routerPrefix+"/studnet/addContact", update.AddStudentContact)
|
||||
app.Post(routerPrefix+"/student/removeContact", update.RemoveStudentContact)
|
||||
app.Post(routerPrefix+"/student/updatePassword", update.UpdateStudentPassword)
|
||||
app.Post(routerPrefix+"/student/resetPassword", update.ResetStudentPassword)
|
||||
app.Post(routerPrefix+"/student/updateAddress", update.UpdateStudentAddress)
|
||||
app.Post(routerPrefix+"/student/updatePhoto", update.UpdateStudentPhoto)
|
||||
app.Post(routerPrefix+"/student/updateEmail", update.UpdateStudentEmail)
|
||||
|
||||
// Student Contact Handler
|
||||
app.Post(routerPrefix+"/student/createContact", controllers.CreateContact)
|
||||
app.Post(routerPrefix+"/student/contact/updateName", controllers.UpdateContactName)
|
||||
app.Post(routerPrefix+"/student/contact/updateAddress", controllers.UpdateContactAddress)
|
||||
app.Post(routerPrefix+"/student/contact/updateHomePhone", controllers.UpdateContactHomePhone)
|
||||
app.Post(routerPrefix+"/student/contact/updateWorkPhone", controllers.UpdateContactWorkPhone)
|
||||
app.Post(routerPrefix+"/student/contact/updateEmail", controllers.UpdateContactEmail)
|
||||
app.Post(routerPrefix+"/student/contact/updatePriority", controllers.UpdateContactPriority)
|
||||
app.Post(routerPrefix+"/student/contact/deleteContact", controllers.DeleteContact)
|
||||
app.Post(routerPrefix+"/contact/createContact", controllers.CreateContact)
|
||||
app.Post(routerPrefix+"/contact/updateName", update.UpdateContactName)
|
||||
app.Post(routerPrefix+"/contact/updateAddress", update.UpdateContactAddress)
|
||||
app.Post(routerPrefix+"/contact/updateHomePhone", update.UpdateContactHomePhone)
|
||||
app.Post(routerPrefix+"/contact/updateWorkPhone", update.UpdateContactWorkPhone)
|
||||
app.Post(routerPrefix+"/contact/updateEmail", update.UpdateContactEmail)
|
||||
app.Post(routerPrefix+"/contact/updatePriority", update.UpdateContactPriority)
|
||||
app.Post(routerPrefix+"/contact/deleteContact", controllers.DeleteContact)
|
||||
|
||||
// Teacher Authentication Handler
|
||||
app.Get(routerPrefix+"/teacher", controllers.Teacher)
|
||||
@@ -56,13 +57,13 @@ func Setup(app *fiber.App) {
|
||||
app.Post(routerPrefix+"/teacher/login", controllers.TeacherLogin)
|
||||
|
||||
// Teacher Update Handler
|
||||
app.Post(routerPrefix+"/teacher/updatePassword", controllers.UpdateTeacherPassword)
|
||||
app.Post(routerPrefix+"/teacher/updateAddress", controllers.UpdateTeacherAddress)
|
||||
app.Post(routerPrefix+"/teacher/updatePhoto", controllers.UpdateTeacherPhoto)
|
||||
app.Post(routerPrefix+"/teacher/updateName", controllers.UpdateTeacherName)
|
||||
app.Post(routerPrefix+"/teacher/updateHomeroom", controllers.UpdateTeacherHomeroom)
|
||||
app.Post(routerPrefix+"/teacher/updateEmail", controllers.UpdateTeacherEmail)
|
||||
app.Post(routerPrefix+"/teacher/resetPassword", controllers.ResetTeacherPassword)
|
||||
app.Post(routerPrefix+"/teacher/updatePassword", update.UpdateTeacherPassword)
|
||||
app.Post(routerPrefix+"/teacher/updateAddress", update.UpdateTeacherAddress)
|
||||
app.Post(routerPrefix+"/teacher/updatePhoto", update.UpdateTeacherPhoto)
|
||||
app.Post(routerPrefix+"/teacher/updateName", update.UpdateTeacherName)
|
||||
app.Post(routerPrefix+"/teacher/updateHomeroom", update.UpdateTeacherHomeroom)
|
||||
app.Post(routerPrefix+"/teacher/updateEmail", update.UpdateTeacherEmail)
|
||||
app.Post(routerPrefix+"/teacher/resetPassword", update.ResetTeacherPassword)
|
||||
|
||||
// General Routes
|
||||
app.Post(routerPrefix+"/logout", controllers.Logout)
|
||||
@@ -73,14 +74,14 @@ func Setup(app *fiber.App) {
|
||||
app.Post(routerPrefix+"/admin/login", controllers.AdminLogin)
|
||||
|
||||
// Admin Update Handler
|
||||
app.Post(routerPrefix+"/admin/updateName", controllers.UpdateAdminName)
|
||||
app.Post(routerPrefix+"/admin/updateEmail", controllers.UpdateAdminEmail)
|
||||
app.Post(routerPrefix+"/admin/updatePassword", controllers.UpdateAdminPassword)
|
||||
app.Post(routerPrefix+"/admin/updateName", update.UpdateAdminName)
|
||||
app.Post(routerPrefix+"/admin/updateEmail", update.UpdateAdminEmail)
|
||||
app.Post(routerPrefix+"/admin/updatePassword", update.UpdateAdminPassword)
|
||||
|
||||
// General Command Handling
|
||||
app.Post(routerPrefix+"/admin/updateLockerCombo", controllers.UpdateLockerCombo)
|
||||
app.Post(routerPrefix+"/admin/enableStudent", controllers.RemoveStudentsDisabled)
|
||||
app.Post(routerPrefix+"/admin/enableTeacher", controllers.RemoveTeachersDisabled)
|
||||
app.Post(routerPrefix+"/admin/updateLockerCombo", update.UpdateLockerCombo)
|
||||
app.Post(routerPrefix+"/admin/enableStudent", update.RemoveStudentsDisabled)
|
||||
app.Post(routerPrefix+"/admin/enableTeacher", update.RemoveTeachersDisabled)
|
||||
|
||||
// Delete Handler
|
||||
app.Post(routerPrefix+"/remove/student", controllers.RemoveStudent)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
dot_import_whitelist = ["github.com/SowinskiBraeden/school-management-api/controllers"]
|
||||
@@ -0,0 +1,95 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width"/>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
<title>Account Registered</title>
|
||||
<style type="text/css">
|
||||
body{
|
||||
margin: 0 auto;
|
||||
padding: 0;
|
||||
min-width: 100%;
|
||||
font-family: sans-serif;
|
||||
}
|
||||
table{
|
||||
margin: 50px 0 50px 0;
|
||||
}
|
||||
.header{
|
||||
height: 40px;
|
||||
text-align: center;
|
||||
text-transform: uppercase;
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.content{
|
||||
height: 100px;
|
||||
font-size: 18px;
|
||||
line-height: 30px;
|
||||
}
|
||||
.subscribe{
|
||||
height: 70px;
|
||||
text-align: center;
|
||||
}
|
||||
.button{
|
||||
text-align: center;
|
||||
font-size: 18px;
|
||||
font-family: sans-serif;
|
||||
font-weight: bold;
|
||||
padding: 0 30px 0 30px;
|
||||
}
|
||||
.button a{
|
||||
color: #FFFFFF;
|
||||
text-decoration: none;
|
||||
}
|
||||
.buttonwrapper{
|
||||
margin: 0 auto;
|
||||
}
|
||||
.footer{
|
||||
text-transform: uppercase;
|
||||
text-align: center;
|
||||
height: 40px;
|
||||
font-size: 14px;
|
||||
font-style: italic;
|
||||
}
|
||||
.footer a{
|
||||
color: #000000;
|
||||
text-decoration: none;
|
||||
font-style: normal;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body bgcolor="#009587">
|
||||
<table bgcolor="#FFFFFF" width="100%" border="0" cellspacing="0" cellpadding="0">
|
||||
<tr class="header">
|
||||
<td style="padding: 40px;">
|
||||
Account Registered
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="content">
|
||||
<td style="padding:10px;">
|
||||
<p>
|
||||
Hi <b>{{ .username }}</b>, <br/>
|
||||
Your account has been registered into the system. You can now log into your account.
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="subscribe">
|
||||
<td style="padding: 20px 0 0 0;">
|
||||
<h3>Your {{ .userType }} ID is:</h3>
|
||||
<table bgcolor="#009587" border="0" cellspacing="0" cellpadding="0" class="buttonwrapper">
|
||||
<tr>
|
||||
<td class="button" height="45">
|
||||
{{ .id }}
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="footer">
|
||||
<td style="padding: 40px;">
|
||||
This is an automated system email // DO NOT REPLY
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,3 +0,0 @@
|
||||
# Testing
|
||||
|
||||
If you would like to view this code more neatly, it has been moved to its own [repository](https://github.com/SowinskiBraeden/schedule-generator).
|
||||
@@ -1,21 +0,0 @@
|
||||
import json
|
||||
|
||||
f = open('./output/students.json')
|
||||
students = json.load(f)
|
||||
f.close()
|
||||
|
||||
couldnt_resolve = 0
|
||||
missing_classes = 0
|
||||
acceptable_missing_classes = 0
|
||||
|
||||
for student in students:
|
||||
blocks = [student["schedule"][block] for block in student["schedule"]]
|
||||
conflicts = sum(1 for b in blocks if len(b)>1)
|
||||
if conflicts == 0 and student["classes"] == student["expectedClasses"]: continue
|
||||
if conflicts > 0: couldnt_resolve += 1
|
||||
if (student["expectedClasses"] - 2) <= student["classes"] < student["expectedClasses"]: acceptable_missing_classes += 1
|
||||
if student["classes"] < (student["expectedClasses"] - 2): missing_classes += 1
|
||||
|
||||
print(f"Couldn't resolve : {couldnt_resolve}/{len(students)} - {round((couldnt_resolve/len(students))*100, 2)}%")
|
||||
print(f"Missing classes : {missing_classes}/{len(students)} - {round((missing_classes/len(students))*100, 2)}%")
|
||||
print(f"Acceptable Missing classes : {acceptable_missing_classes}/{len(students)} - {round((acceptable_missing_classes/len(students))*100, 2)}%")
|
||||
@@ -1,197 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
from util.courses import mockCourses, activeCourses # Fake courses
|
||||
from util.mockStudents import generateMockStudents # Generate fake students
|
||||
import json
|
||||
|
||||
|
||||
'''
|
||||
Block 1-4 is first semester while
|
||||
block 5-8 is second semester
|
||||
'''
|
||||
|
||||
'''
|
||||
schedule example:
|
||||
schedule: {
|
||||
"block1": "className",
|
||||
"block2": "className",
|
||||
"block3": "className",
|
||||
"block4": "className"
|
||||
"block5": "className",
|
||||
"block6": "className",
|
||||
"block7": "className",
|
||||
"block8": "className"
|
||||
}
|
||||
'''
|
||||
|
||||
'''
|
||||
running example:
|
||||
running: {
|
||||
"block1": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block2": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block3": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block4": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block5": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block6": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block7": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block8": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}}
|
||||
}
|
||||
'''
|
||||
|
||||
# Error 1: No classes in schedule can fit this student
|
||||
# Error 2: No more room in schedule for another class
|
||||
|
||||
minReq, median, classCap, blockClassLimit = 18, 24, 30, 12
|
||||
activeCourses = {}
|
||||
running = {
|
||||
"block1": {},
|
||||
"block2": {},
|
||||
"block3": {},
|
||||
"block4": {},
|
||||
"block5": {},
|
||||
"block6": {},
|
||||
"block7": {},
|
||||
"block8": {}
|
||||
}
|
||||
|
||||
# Currently V1 has an average of 9.4% success rate, with an avverage of 90.6% error rate
|
||||
def generateScheduleV1(mockStudents, mockCourses):
|
||||
# Collect data and calculate schedules
|
||||
for student in mockStudents:
|
||||
# Tally class request
|
||||
for request in student["requests"]:
|
||||
mockCourses[request]["totalrequests"] += 1
|
||||
mockCourses[request]["studentindexes"].append(mockStudents.index(student))
|
||||
# Add course to active list if enough requests
|
||||
if mockCourses[request]["totalrequests"] > minReq and mockCourses[request]["code"] not in activeCourses: activeCourses[mockCourses[request]["code"]] = mockCourses[request]
|
||||
|
||||
for student in mockStudents:
|
||||
alternateOffset = len(student["requests"])-8
|
||||
alternateIndex = 8
|
||||
for i in range(len(student["requests"])-alternateOffset): # Subtract x classes as they are alternatives
|
||||
currentCourse = student["requests"][i]
|
||||
generate = True
|
||||
while generate:
|
||||
# If class is allowed to run
|
||||
if currentCourse in activeCourses:
|
||||
blockIndex = 1
|
||||
courseNum = 1
|
||||
getFreeBlock = True
|
||||
while getFreeBlock:
|
||||
block = f"block{blockIndex}"
|
||||
cname = f"{mockCourses[currentCourse]['name']}-{courseNum}"
|
||||
if cname in running[block]:
|
||||
if student["schedule"][block] == "": # Add student to class
|
||||
if len(running[block][cname]["students"]) < classCap:
|
||||
running[block][cname]["students"].append(student["name"])
|
||||
student["schedule"][block] = cname
|
||||
getFreeBlock = False
|
||||
else: # Find next available class or create new one
|
||||
if blockIndex == 8: # No available classes
|
||||
if len(student["requests"]) == 8:
|
||||
# This student never had any alternatives
|
||||
# How to solve?
|
||||
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
else:
|
||||
if alternateIndex <= (len(student["requests"]) - 1):
|
||||
currentCourse = student["requests"][alternateIndex]
|
||||
alternateIndex += 1
|
||||
else: # No more alterantive
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
getFreeBlock = False
|
||||
else:
|
||||
if (mockCourses[currentCourse]["teachers"] - courseNum) > 0:
|
||||
courseNum += 1
|
||||
else:
|
||||
blockIndex += 1
|
||||
courseNum = 1
|
||||
else:
|
||||
if blockIndex == 8: # No available classes
|
||||
if len(student["requests"]) == 8:
|
||||
# This student never had any alternatives
|
||||
# How to solve?
|
||||
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
err1 += 1
|
||||
generate = False
|
||||
else:
|
||||
if alternateIndex <= (len(student["requests"]) - 1):
|
||||
currentCourse = student["requests"][alternateIndex]
|
||||
alternateIndex += 1
|
||||
else: # No more alternatives
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
getFreeBlock = False
|
||||
else:
|
||||
blockIndex += 1
|
||||
courseNum = 1
|
||||
else:
|
||||
if blockIndex == 8:
|
||||
# Class does not exists
|
||||
# Create new class in first available slot
|
||||
blockNum = 1
|
||||
while True:
|
||||
newBlock = f"block{blockNum}"
|
||||
if cname not in running[newBlock] and len(running[newBlock]) < blockClassLimit:
|
||||
if student["schedule"][newBlock] == "": # Add student to class
|
||||
running[newBlock][cname] = {
|
||||
"name": mockCourses[currentCourse]["name"],
|
||||
"students": [student["name"]]
|
||||
}
|
||||
student["schedule"][newBlock] = cname
|
||||
break
|
||||
else:
|
||||
if blockNum == 8:
|
||||
# All student classes have been filled
|
||||
break
|
||||
else:
|
||||
blockNum += 1
|
||||
courseNum = 1
|
||||
else:
|
||||
if blockNum == 8:
|
||||
# No room in school for more classes
|
||||
# print(f"\nError 2: No more room in school for another class")
|
||||
break
|
||||
else:
|
||||
if (mockCourses[currentCourse]["teachers"] - courseNum) > 0:
|
||||
courseNum += 1
|
||||
else:
|
||||
blockNum += 1
|
||||
courseNum = 1
|
||||
break
|
||||
else:
|
||||
blockIndex += 1
|
||||
courseNum = 1
|
||||
break
|
||||
elif currentCourse not in activeCourses:
|
||||
if len(student["requests"]) == 8:
|
||||
# This student never had any alternatives
|
||||
# How to solve?
|
||||
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
else:
|
||||
if alternateIndex <= (len(student["requests"]) - 1):
|
||||
currentCourse = student["requests"][alternateIndex]
|
||||
alternateIndex += 1
|
||||
else: # Out of alternatives
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
|
||||
return running
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("Processing...")
|
||||
|
||||
mockStudents = generateMockStudents(400)
|
||||
timetable = {}
|
||||
timetable["Version"] = 1
|
||||
timetable["timetable"] = generateScheduleV1(mockStudents, mockCourses)
|
||||
|
||||
with open("../output/timetable.json", "w") as outfile:
|
||||
json.dump(timetable, outfile, indent=2)
|
||||
|
||||
print("Done")
|
||||
@@ -1,213 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
from util.courses import mockCourses, activeCourses # Fake courses
|
||||
from util.mockStudents import generateMockStudents # Generate fake students
|
||||
import math
|
||||
import json
|
||||
|
||||
|
||||
'''
|
||||
Block 1-4 is first semester while
|
||||
block 5-8 is second semester
|
||||
'''
|
||||
|
||||
'''
|
||||
schedule example:
|
||||
schedule: {
|
||||
"block1": "className",
|
||||
"block2": "className",
|
||||
"block3": "className",
|
||||
"block4": "className"
|
||||
"block5": "className",
|
||||
"block6": "className",
|
||||
"block7": "className",
|
||||
"block8": "className"
|
||||
}
|
||||
'''
|
||||
|
||||
'''
|
||||
running example:
|
||||
running: {
|
||||
"block1": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block2": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block3": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block4": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block5": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block6": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block7": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block8": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
minReq, median, classCap, blockClassLimit = 18, 24, 30, 12
|
||||
mockStudents = []
|
||||
activeCourses = {}
|
||||
running = {
|
||||
"block1": {},
|
||||
"block2": {},
|
||||
"block3": {},
|
||||
"block4": {},
|
||||
"block5": {},
|
||||
"block6": {},
|
||||
"block7": {},
|
||||
"block8": {}
|
||||
}
|
||||
|
||||
|
||||
# Currently V2 has an average of 0.35% success rate, with an avverage of 99.65% error rate
|
||||
def generateScheduleV2(mockStudents, mockCourses):
|
||||
# Collect data and calculate schedules
|
||||
for student in mockStudents:
|
||||
# Tally class request
|
||||
for request in student["requests"]:
|
||||
mockCourses[request]["totalrequests"] += 1
|
||||
mockCourses[request]["studentindexes"].append(mockStudents.index(student))
|
||||
# Add course to active list if enough requests
|
||||
if mockCourses[request]["totalrequests"] > minReq and mockCourses[request]["code"] not in activeCourses: activeCourses[mockCourses[request]["code"]] = mockCourses[request]
|
||||
|
||||
# calculate # of times to run class
|
||||
for i in range(len(activeCourses)):
|
||||
index = list(activeCourses)[i]
|
||||
classRunCount = math.floor(activeCourses[index]["totalrequests"] / classCap)
|
||||
# If there is minReq+ requests left, 1 more class could be run
|
||||
if (activeCourses[index]["totalrequests"] % classCap) > minReq: classRunCount += 1
|
||||
activeCourses[index]["classRunCount"] = classRunCount
|
||||
|
||||
newBlockIndex = 1
|
||||
newCourseNum = 1
|
||||
while classRunCount > 0:
|
||||
block = f"block{newBlockIndex}"
|
||||
cname = f"{activeCourses[index]['name']}-{newCourseNum}"
|
||||
if cname not in running[block] and len(running[block]) < blockClassLimit:
|
||||
# Generate class and sub 1 from classRunCount
|
||||
running[block][cname] = {
|
||||
"name": activeCourses[index]["name"],
|
||||
"students": []
|
||||
}
|
||||
classRunCount -= 1
|
||||
else:
|
||||
if newBlockIndex == 8:
|
||||
if (activeCourses[index]["teachers"] - newCourseNum) > 0:
|
||||
newCourseNum += 1
|
||||
newBlockIndex = 1
|
||||
else:
|
||||
# No room in school for more classes
|
||||
# print(f"\nError 2: No more room in school for another class")
|
||||
classRunCount = 0
|
||||
else: newBlockIndex += 1
|
||||
|
||||
for student in mockStudents:
|
||||
alternateOffset = len(student["requests"])-8
|
||||
alternateIndex = 8
|
||||
for i in range(len(student["requests"])-alternateOffset): # Subtract x classes as they are alternatives
|
||||
currentCourse = student["requests"][i]
|
||||
generate = True
|
||||
courseNum = 1
|
||||
while generate:
|
||||
# If class is allowed to run
|
||||
if currentCourse in activeCourses:
|
||||
blockIndex = 1
|
||||
getFreeBlock = True
|
||||
cname = f"{mockCourses[currentCourse]['name']}-{courseNum}"
|
||||
while getFreeBlock:
|
||||
block = f"block{blockIndex}"
|
||||
if cname in running[block]:
|
||||
if student["schedule"][block] == "": # Add student to class
|
||||
if len(running[block][cname]["students"]) < classCap:
|
||||
running[block][cname]["students"].append(student["name"])
|
||||
student["schedule"][block] = cname
|
||||
getFreeBlock = False
|
||||
else: # Find next available class or create new one
|
||||
if blockIndex == 8: # No available classes
|
||||
if (activeCourses[index]["teachers"] - newCourseNum) > 0:
|
||||
newCourseNum += 1
|
||||
newBlockIndex = 1
|
||||
else:
|
||||
# No room in school for more classes
|
||||
# print(f"\nError 2: No more room in school for another class")
|
||||
classRunCount = 0
|
||||
if len(student["requests"]) == 8:
|
||||
# This student never had any alternatives
|
||||
# How to solve?
|
||||
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
else:
|
||||
if alternateIndex <= (len(student["requests"]) - 1):
|
||||
currentCourse = student["requests"][alternateIndex]
|
||||
alternateIndex += 1
|
||||
else: # No more alterantive
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
getFreeBlock = False
|
||||
else: blockIndex += 1
|
||||
else:
|
||||
if blockIndex == 8: # No available classes
|
||||
if len(student["requests"]) == 8:
|
||||
# This student never had any alternatives
|
||||
# How to solve?
|
||||
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
else:
|
||||
if alternateIndex <= (len(student["requests"]) - 1):
|
||||
currentCourse = student["requests"][alternateIndex]
|
||||
alternateIndex += 1
|
||||
else: # No more alternatives
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
getFreeBlock = False
|
||||
else:
|
||||
if (mockCourses[currentCourse]["teachers"] - courseNum) > 0:
|
||||
courseNum += 1
|
||||
else:
|
||||
blockIndex += 1
|
||||
courseNum = 1
|
||||
else:
|
||||
if blockIndex == 8:
|
||||
# Class does not exists
|
||||
# Resort to alternative
|
||||
if alternateIndex <= (len(student["requests"]) - 1):
|
||||
currentCourse = student["requests"][alternateIndex]
|
||||
alternateIndex += 1
|
||||
else: # Out of alternatives
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
break
|
||||
else:
|
||||
if (mockCourses[currentCourse]["teachers"] - courseNum) > 0:
|
||||
courseNum += 1
|
||||
else:
|
||||
blockIndex += 1
|
||||
courseNum = 1
|
||||
break
|
||||
elif currentCourse not in activeCourses:
|
||||
if len(student["requests"]) == 8:
|
||||
# This student never had any alternatives
|
||||
# How to solve?
|
||||
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
else:
|
||||
if alternateIndex <= (len(student["requests"]) - 1):
|
||||
currentCourse = student["requests"][alternateIndex]
|
||||
alternateIndex += 1
|
||||
else: # Out of alternatives
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
|
||||
return running
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("Processing...")
|
||||
|
||||
mockStudents = generateMockStudents(400)
|
||||
timetable = {}
|
||||
timetable["Version"] = 2
|
||||
timetable["timetable"] = generateScheduleV2(mockStudents, mockCourses)
|
||||
|
||||
with open("../output/timetable.json", "w") as outfile:
|
||||
json.dump(timetable, outfile, indent=2)
|
||||
|
||||
print("Done")
|
||||
@@ -1,613 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
from inspect import currentframe
|
||||
|
||||
from click import pass_context
|
||||
|
||||
# Import from custom utilities
|
||||
from util.mockStudents import getSampleStudents
|
||||
from util.generateCourses import getSampleCourses
|
||||
|
||||
|
||||
'''
|
||||
Block 1-5 is first semester while
|
||||
block 6-10 is second semester
|
||||
|
||||
|
||||
schedule example:
|
||||
schedule: {
|
||||
"block1": "className",
|
||||
"block2": "className",
|
||||
"block3": "className",
|
||||
...
|
||||
}
|
||||
|
||||
|
||||
running example:
|
||||
running: {
|
||||
"block1": {
|
||||
classCode: {
|
||||
"className": name,
|
||||
"students": [student Name]
|
||||
},
|
||||
classCode: {
|
||||
"className": name,
|
||||
"students": [student Name]
|
||||
}
|
||||
},
|
||||
...
|
||||
}
|
||||
'''
|
||||
|
||||
def getLineNumber(): return currentframe().f_back.f_lineno
|
||||
|
||||
# Takes in information to create or add a new conflict
|
||||
# Returns if the particular student has a previous error
|
||||
def newConflict(pupilNum: str, email: str, type: str, code: str, description: str, logs: dict) -> bool:
|
||||
exists = True if pupilNum in logs else False
|
||||
if exists: logs[pupilNum].append({
|
||||
"Pupil #": pupilNum,
|
||||
"Email": email,
|
||||
"Type": type,
|
||||
"Code": code,
|
||||
"Conflict": description
|
||||
})
|
||||
else:
|
||||
logs[pupilNum] = [{
|
||||
"Pupil #": pupilNum,
|
||||
"Email": email,
|
||||
"Type": type,
|
||||
"Code": code,
|
||||
"Conflict": description
|
||||
}]
|
||||
return exists
|
||||
|
||||
minReq, median, classCap = 18, 24, 30
|
||||
activeCourses = {}
|
||||
running = {
|
||||
"block1": {},
|
||||
"block2": {},
|
||||
"block3": {},
|
||||
"block4": {},
|
||||
"block5": {},
|
||||
"block6": {},
|
||||
"block7": {},
|
||||
"block8": {},
|
||||
"block9": {},
|
||||
"block10": {}
|
||||
}
|
||||
|
||||
# These are the codes for Flex (spare) blocks
|
||||
# Semester 1 and 2
|
||||
flex = ["XAT--12A-S", "XAT--12B-S"]
|
||||
|
||||
# V3 differs a lot by V1/2 as it does not focus on fitting the classes
|
||||
# into the time table first.
|
||||
# It starts by trying to get all classes full and give all students a full class list.
|
||||
# Then it starts to attempt to fit all classes into a timetable, making corretions along
|
||||
# the way. Corrections being moving a students class
|
||||
def generateScheduleV3(
|
||||
students: list,
|
||||
courses: dict,
|
||||
blockClassLimit: int=40,
|
||||
studentsDir: str="../output/students.json",
|
||||
conflictsDir: str="../output/conflicts.json"
|
||||
) -> dict[str, dict]:
|
||||
|
||||
def equal(l: list) -> list: # Used to equalize list of numbers
|
||||
q,r = divmod(sum(l),len(l))
|
||||
return [q+1]*r + [q]*(len(l)-r)
|
||||
|
||||
|
||||
# Step 1 - Calculate which classes can run
|
||||
for student in students:
|
||||
# Tally class request
|
||||
for request in (request for request in student["requests"] if not request["alt"] and request["CrsNo"] not in flex):
|
||||
code = request["CrsNo"]
|
||||
courses[code]["Requests"] += 1
|
||||
# Add course to active list if enough requests
|
||||
if courses[code]["Requests"] > minReq and courses[code]["CrsNo"] not in activeCourses:
|
||||
activeCourses[code] = courses[code]
|
||||
|
||||
|
||||
# Step 2 - Generate empty classes
|
||||
allClassRunCounts = []
|
||||
courseRunInfo = {} # Generated now, used in step 4
|
||||
emptyClasses = {} # List of all classes with how many students should be entered during step 3
|
||||
# calculate # of times to run class
|
||||
for i in range(len(activeCourses)):
|
||||
index = list(activeCourses)[i]
|
||||
if index not in emptyClasses: emptyClasses[index] = {}
|
||||
classRunCount = math.floor(activeCourses[index]["Requests"] / median)
|
||||
remaining = activeCourses[index]["Requests"] % median
|
||||
|
||||
# Put # of classRunCount classes in emptyClasses
|
||||
for j in range(classRunCount):
|
||||
emptyClasses[index][f"{index}-{j}"] = {
|
||||
"CrsNo": index,
|
||||
"Description": activeCourses[index]["Description"],
|
||||
"expectedLen": median # Number of students expected in this class / may be altered
|
||||
}
|
||||
|
||||
# If remaining fit in open slots in existing classes
|
||||
if remaining <= classRunCount * (classCap - median):
|
||||
# Equally disperse remaining into existing classes
|
||||
while remaining > 0:
|
||||
for j in range(classRunCount):
|
||||
if remaining == 0: break
|
||||
emptyClasses[index][f"{index}-{j}"]["expectedLen"] += 1
|
||||
remaining -= 1
|
||||
|
||||
# If we can create a class using remaining, but no other classes
|
||||
# exists, create class, and do not equalize
|
||||
elif remaining >= minReq:
|
||||
# Create a class using remaining
|
||||
emptyClasses[index][f"{index}-{classRunCount}"] = {
|
||||
"CrsNo": index,
|
||||
"Description": activeCourses[index]["Description"],
|
||||
"expectedLen": remaining
|
||||
}
|
||||
|
||||
classRunCount += 1
|
||||
if classRunCount >= 2:
|
||||
# Equalize (level) class expectedLen's
|
||||
expectedLengths = [emptyClasses[index][f"{index}-{j}"]["expectedLen"] for j in range(classRunCount)]
|
||||
newExpectedLens = equal(expectedLengths)
|
||||
for j in range(len(newExpectedLens)):
|
||||
emptyClasses[index][f"{index}-{j}"]["expectedLen"] = newExpectedLens[j]
|
||||
|
||||
# Else if we can't fit remaining in open slots in existing classes
|
||||
# and it is unable to create its own class,
|
||||
# and requiered number to make a class is less than the max number we can provide from existing classes
|
||||
elif minReq - remaining < classRunCount * (median - minReq):
|
||||
# Take 1 from each class till min requirment met
|
||||
for j in range(classRunCount):
|
||||
emptyClasses[index][f"{index}-{j}"]["expectedLen"] -= 1
|
||||
remaining += 1
|
||||
if remaining == minReq: break
|
||||
|
||||
# Create a class using remaining
|
||||
emptyClasses[index][f"{index}-{classRunCount}"] = {
|
||||
"CrsNo": index,
|
||||
"Description": activeCourses[index]["Description"],
|
||||
"expectedLen": remaining
|
||||
}
|
||||
|
||||
classRunCount += 1
|
||||
|
||||
# Equalize (level) class expectedLen's
|
||||
expectedLengths = [emptyClasses[index][f"{index}-{j}"]["expectedLen"] for j in range(classRunCount)]
|
||||
newExpectedLens = equal(expectedLengths)
|
||||
for j in range(len(newExpectedLens)):
|
||||
emptyClasses[index][f"{index}-{j}"]["expectedLen"] = newExpectedLens[j]
|
||||
|
||||
else:
|
||||
# In the case that the remaining requests are unable to be resolved
|
||||
# Fill as many requests into class as possible, any left that can't fit,
|
||||
# Will need to be ignored so later we can fold them into their alternative
|
||||
# choices
|
||||
for j in range(classRunCount):
|
||||
if emptyClasses[index][f"{index}-{j}"]["expectedLen"] < classCap and remaining > 0:
|
||||
emptyClasses[index][f"{index}-{j}"]["expectedLen"] += 1
|
||||
remaining -= 1
|
||||
|
||||
courseRunInfo[index] = {
|
||||
"Total": classRunCount,
|
||||
"CrsNo": index
|
||||
}
|
||||
allClassRunCounts.append(classRunCount)
|
||||
|
||||
|
||||
# Step 3 Fill emptyClasses with Students
|
||||
selectedCourses = {}
|
||||
tempStudents = list(students)
|
||||
|
||||
while len(tempStudents) > 0:
|
||||
student = tempStudents[random.randint(0, len(tempStudents)-1)]
|
||||
|
||||
alternates = [request for request in student["requests"] if request["alt"]]
|
||||
for request in (request for request in student["requests"] if not request["alt"] and request["CrsNo"] not in flex):
|
||||
course = request["CrsNo"]
|
||||
getAvailableCourse = True
|
||||
isAlt = False
|
||||
while getAvailableCourse:
|
||||
if course in emptyClasses:
|
||||
# if course exists, get first available class
|
||||
for cname in emptyClasses[course]:
|
||||
if cname in selectedCourses:
|
||||
if isAlt and emptyClasses[course][cname]["expectedLen"] < classCap:
|
||||
emptyClasses[course][cname]["expectedLen"] += 1
|
||||
if len(selectedCourses[cname]["students"]) < emptyClasses[course][cname]["expectedLen"]:
|
||||
# Class exists with room for student
|
||||
selectedCourses[cname]["students"].append({
|
||||
"Pupil #": student["Pupil #"],
|
||||
"index": student["studentIndex"]
|
||||
})
|
||||
getAvailableCourse = False
|
||||
break
|
||||
elif len(selectedCourses[cname]["students"]) == emptyClasses[course][cname]["expectedLen"]:
|
||||
# If class is full, and is last class of that course
|
||||
if cname[len(cname)-1] == f"{len(emptyClasses[course])-1}":
|
||||
if len(alternates) > 0:
|
||||
# Use alternate
|
||||
course = alternates[0]["CrsNo"]
|
||||
alternates.remove(alternates[0])
|
||||
isAlt = True
|
||||
break
|
||||
else:
|
||||
# Force break loop, ignore and let an admin
|
||||
# handle options to solve for missing class
|
||||
getAvailableCourse = False
|
||||
break
|
||||
elif cname not in selectedCourses:
|
||||
selectedCourses[cname] = {
|
||||
"students": [{
|
||||
"Pupil #": student["Pupil #"],
|
||||
"index": student["studentIndex"]
|
||||
}],
|
||||
"CrsNo": course,
|
||||
"Description": courses[course]["Description"]
|
||||
}
|
||||
getAvailableCourse = False
|
||||
break
|
||||
|
||||
elif course not in emptyClasses:
|
||||
if len(alternates) > 0:
|
||||
# Use alternate
|
||||
course = alternates[0]["CrsNo"]
|
||||
alternates.remove(alternates[0])
|
||||
isAlt = True
|
||||
else:
|
||||
# Force break loop, ignore and let an admin
|
||||
# handle options to solve for missing class
|
||||
getAvailableCourse = False
|
||||
|
||||
students[student["studentIndex"]]["remainingAlts"] = alternates
|
||||
tempStudents.remove(student)
|
||||
|
||||
|
||||
# Step 4 - Attempt to fit classes into timetable
|
||||
def stepIndex(offset: int, stepType: int) -> int:
|
||||
# stepType 0 is for stepping between first and second semester
|
||||
if stepType == 0:
|
||||
if offset == 0 or offset == -4: return 5
|
||||
else: return -4
|
||||
|
||||
# stepType 1 is for stepping between second and first semester
|
||||
elif stepType == 1:
|
||||
if offset == 0 or offset == 6: return -5
|
||||
else: return 6
|
||||
|
||||
# Return Error if code is altered to cause error
|
||||
else: raise SystemExit(f"Invalid 'stepType' in func 'stepIndex' line {getLineNumber()}")
|
||||
|
||||
while len(allClassRunCounts) > 0:
|
||||
# Get highest resource class (most times run)
|
||||
index = allClassRunCounts.index(min(allClassRunCounts))
|
||||
course = list(courseRunInfo)[index]
|
||||
|
||||
# Tally first and second semester
|
||||
sem1, sem2 = 0, 0
|
||||
sem1List, sem2List = {}, {}
|
||||
for i in range(1, 6):
|
||||
sem1 += len(running[f"block{i}"])
|
||||
sem1List[f"block{i}"] = running[f"block{i}"]
|
||||
for i in range(5, 11):
|
||||
sem2 += len(running[f"block{i}"])
|
||||
sem2List[f"block{i}"] = running[f"block{i}"]
|
||||
|
||||
# If there is more than one class Running
|
||||
if allClassRunCounts[index] > 1:
|
||||
blockIndex = 0 if sem1 <= sem2 else 5
|
||||
stepType = 0 if sem1 <= sem2 else 1
|
||||
offset = 0
|
||||
|
||||
# Spread classes throughout both semesters
|
||||
for i in range(courseRunInfo[course]["Total"]):
|
||||
cname = f"{course}-{i}"
|
||||
classInserted = False
|
||||
while not classInserted:
|
||||
|
||||
blockIndex += offset
|
||||
if len(running[list(running)[blockIndex]]) < blockClassLimit:
|
||||
running[list(running)[blockIndex]][cname] = {
|
||||
"CrsNo": course,
|
||||
"Description": emptyClasses[course][cname]["Description"],
|
||||
"students": selectedCourses[cname]["students"]
|
||||
}
|
||||
allClassRunCounts[index] -= 1
|
||||
classInserted = True
|
||||
|
||||
offset = stepIndex(offset, stepType)
|
||||
|
||||
if blockIndex >= 9:
|
||||
blockIndex = 0 if sem1 <= sem2 else 5
|
||||
offset = 0
|
||||
|
||||
# If the class only runs once, place in semester with least classes
|
||||
elif allClassRunCounts[index] == 1:
|
||||
# Equally disperse into semesters classes
|
||||
semBlocks = []
|
||||
offset = 1
|
||||
|
||||
# If sem1 is less than or equal to sem2, add to sem1
|
||||
if sem1 <= sem2:
|
||||
for block in sem1List:
|
||||
semBlocks.append(len(block))
|
||||
|
||||
# If sem2 is less than sem1, add to sem2
|
||||
elif sem1 > sem2:
|
||||
offset = 5
|
||||
for block in sem2List:
|
||||
semBlocks.append(len(block))
|
||||
|
||||
# Get block with least classes
|
||||
leastBlock = semBlocks.index(min(semBlocks))
|
||||
cname = f"{course}-0"
|
||||
|
||||
running[f"block{leastBlock+offset}"][course] = {
|
||||
"CrsNo": course,
|
||||
"Description": emptyClasses[course][cname]["Description"],
|
||||
"students": selectedCourses[cname]["students"],
|
||||
}
|
||||
|
||||
allClassRunCounts[index] -= 1
|
||||
|
||||
# Remove course when fully inserted
|
||||
if allClassRunCounts[index] == 0:
|
||||
allClassRunCounts.remove(allClassRunCounts[index])
|
||||
courseRunInfo.pop(list(courseRunInfo)[index])
|
||||
|
||||
|
||||
# Step 5 - Fill student schedule
|
||||
for block in running:
|
||||
for cname in running[block]:
|
||||
for student in running[block][cname]["students"]:
|
||||
students[student["index"]]["schedule"][block].append(cname)
|
||||
students[student["index"]]["classes"] += 1
|
||||
|
||||
|
||||
# Step 6 - Evaluate, move students to fix conflicts
|
||||
conflictLogs = {}
|
||||
criticalCount, acceptableCount = 0, 0
|
||||
c_mc_count, c_cr_count, a_mc_count = 0, 0, 0
|
||||
studentsCritical, studentsAcceptable = 0, 0
|
||||
|
||||
for student in students:
|
||||
initialBlocks = [student["schedule"][block] for block in student["schedule"]]
|
||||
conflicts = sum(1 for b in initialBlocks if len(b)>1)
|
||||
hasConflicts = True if conflicts > 0 else False
|
||||
|
||||
# If there is no conflicts
|
||||
# and classes inserted to is equal to expectedClasses
|
||||
# or classes the student is inserted to is missing
|
||||
# no more than two classes:
|
||||
# continue to next student
|
||||
if not hasConflicts and student["classes"] == student["expectedClasses"]: continue
|
||||
elif not hasConflicts and (student["expectedClasses"]-2) <= student["classes"] < student["expectedClasses"]:
|
||||
a_mc_count += 1
|
||||
acceptableCount += 1
|
||||
if not newConflict(student["Pupil #"], "", "Acceptable", "A-MC", "Missing 1-2 Classses", conflictLogs): studentsAcceptable += 1
|
||||
continue
|
||||
|
||||
studentData = {
|
||||
"Pupil #": student["Pupil #"],
|
||||
"index": student["studentIndex"]
|
||||
}
|
||||
|
||||
# If we are unable to solve, we add to exceptions
|
||||
# and keep trying to resolve the rest of the schedule
|
||||
exceptions = []
|
||||
|
||||
while hasConflicts:
|
||||
# Check if conflicts have been resolved
|
||||
blocks = [student["schedule"][block] for block in student["schedule"]]
|
||||
# If there is exceptions, make them look normal in blocks
|
||||
# list to ginore them when looking for clashes, and not to
|
||||
# accidently overwrite while evaluating other classes
|
||||
if len(exceptions) > 0:
|
||||
for i in range(len(blocks)):
|
||||
if i in exceptions: blocks[i] = ['EXPT']
|
||||
conflicts = sum(1 for b in blocks if len(b)>1)
|
||||
|
||||
if conflicts == 0: hasConflicts = False
|
||||
|
||||
elif conflicts > 0:
|
||||
|
||||
blockLens = [len(block) for block in blocks]
|
||||
freeBlocks = [index for index in range(len(blocks)) if len(blocks[index]) == 0]
|
||||
|
||||
clashIndex = blockLens.index(max(blockLens))
|
||||
blockOut = f"block{clashIndex+1}"
|
||||
classIndex = 0
|
||||
done, advancedConflict = False, False
|
||||
|
||||
while not done:
|
||||
classOut = blocks[clashIndex][classIndex]
|
||||
found = False
|
||||
for index in freeBlocks:
|
||||
if found: break
|
||||
if index != clashIndex:
|
||||
blockIn = list(running)[index]
|
||||
for cname in running[blockIn]:
|
||||
if cname[:-2] == classOut[:-2] and len(running[blockIn][cname]["students"]) < classCap:
|
||||
|
||||
# Update records
|
||||
student["schedule"][blockOut].remove(classOut)
|
||||
student["schedule"][blockIn].append(cname)
|
||||
|
||||
running[blockOut][classOut]["students"].remove(studentData)
|
||||
running[blockIn][cname]["students"].append(studentData)
|
||||
|
||||
found = True
|
||||
break
|
||||
|
||||
if not found:
|
||||
if classIndex < len(blocks[clashIndex])-1: classIndex += 1
|
||||
elif classIndex == len(blocks[clashIndex])-1:
|
||||
classIndex = 0
|
||||
advancedConflict = True
|
||||
done = True
|
||||
else:
|
||||
print(f"Fatal error ({getLineNumber()}): Impossible error")
|
||||
continue
|
||||
|
||||
elif found: done = True
|
||||
|
||||
if advancedConflict:
|
||||
attemptResolve = True
|
||||
classOutIndex = 0
|
||||
while attemptResolve:
|
||||
foundSolution = False
|
||||
newClassOut = blocks[clashIndex][classOutIndex]
|
||||
for blockIndex in range(len(running)):
|
||||
if foundSolution: break
|
||||
if blockIndex != clashIndex and blockIndex not in exceptions:
|
||||
for cname in running[list(running)[blockIndex]]:
|
||||
if cname[:-2] == newClassOut[:-2]:
|
||||
blockIn = f"block{blockIndex+1}"
|
||||
if blockIndex in freeBlocks:
|
||||
if len(running[blockIn][cname]["students"]) < classCap:
|
||||
# In the rare or impossible case a student was not inserted to a class
|
||||
# And it weren't full, insert them into the class
|
||||
student["schedule"][blockOut].remove(newClassOut)
|
||||
student["schedule"][blockIn].append(cname)
|
||||
|
||||
running[blockOut][newClassOut]["students"].remove(studentData)
|
||||
running[blockIn][cname]["students"].append(studentData)
|
||||
foundSolution = True
|
||||
break
|
||||
|
||||
elif len(blocks[blockIndex]) == 1:
|
||||
oClassOut = blocks[blockIndex][0]
|
||||
found_oBlockSolution = False
|
||||
for oBlockIndex in range(len(running)):
|
||||
if found_oBlockSolution: break
|
||||
if oBlockIndex != clashIndex and oBlockIndex not in exceptions and oBlockIndex in freeBlocks:
|
||||
for ocname in running[list(running)[oBlockIndex]]:
|
||||
if ocname[:-2] == oClassOut[:-2]:
|
||||
oBlockIn = f"block{oBlockIndex+1}"
|
||||
if len(running[oBlockIn][ocname]["students"]) < classCap:
|
||||
student["schedule"][blockOut].remove(newClassOut)
|
||||
student["schedule"][blockIn].append(cname)
|
||||
student["schedule"][blockIn].remove(oClassOut)
|
||||
student["schedule"][oBlockIn].append(ocname)
|
||||
|
||||
running[blockOut][newClassOut]["students"].remove(studentData)
|
||||
running[blockIn][cname]["students"].append(studentData)
|
||||
running[blockIn][oClassOut]["students"].remove(studentData)
|
||||
running[oBlockIn][ocname]["students"].append(studentData)
|
||||
|
||||
found_oBlockSolution = True
|
||||
break
|
||||
|
||||
|
||||
if not found_oBlockSolution:
|
||||
exceptions.append(clashIndex)
|
||||
criticalCount += 1
|
||||
c_cr_count += 1
|
||||
if not newConflict(student["Pupil #"], "", "Critial", "C-CR", "Couldn't Resolve", conflictLogs): studentsCritical += 1
|
||||
|
||||
foundSolution = True
|
||||
break
|
||||
|
||||
if not foundSolution:
|
||||
if classOutIndex < len(blocks[clashIndex]) - 1: classOutIndex += 1
|
||||
elif classOutIndex == len(blocks[clashIndex]) - 1:
|
||||
if len(student["remainingAlts"]) > 0:
|
||||
exceptions.append(clashIndex)
|
||||
criticalCount += 1
|
||||
c_cr_count += 1
|
||||
if not newConflict(student["Pupil #"], "", "Critical", "C-CR", "Couldn't Resolve", conflictLogs): studentsCritical += 1
|
||||
|
||||
attemptResolve = False
|
||||
# Attempt to use alt
|
||||
elif len(student["remainingAlts"]) == 0:
|
||||
exceptions.append(clashIndex)
|
||||
criticalCount += 1
|
||||
c_cr_count += 1
|
||||
if not newConflict(student["Pupil #"], "", "Critical", "C-CR", "Couldn't Resolve", conflictLogs): studentsCritical += 1
|
||||
|
||||
attemptResolve = False
|
||||
else: print("Impossible - Thanos")
|
||||
elif foundSolution:
|
||||
attemptResolve = False
|
||||
|
||||
else:
|
||||
print(f"Fatal error ({getLineNumber()}): Impossible error")
|
||||
continue
|
||||
|
||||
metSelfRequirements = True if student["classes"] == student["expectedClasses"] else False
|
||||
while not metSelfRequirements:
|
||||
|
||||
if (student["expectedClasses"] - 2) <= student["classes"] < student["expectedClasses"]:
|
||||
a_mc_count += 1
|
||||
acceptableCount += 1
|
||||
if not newConflict(student["Pupil #"], "", "Acceptable", "A-MC", "Missing 1-2 Classses", conflictLogs): studentsAcceptable += 1
|
||||
break
|
||||
|
||||
elif student["classes"] < (student["expectedClasses"] - 2):
|
||||
# Difference between classes inserted to and
|
||||
# expected classes is too great, attempt to fix
|
||||
if student["Pupil #"] in conflictLogs:
|
||||
c_mc_count += 1
|
||||
criticalCount += 1
|
||||
if not newConflict(student["Pupil #"], "", "Critical", "C-MC", "Missing too many Classses", conflictLogs): studentsCritical += 1
|
||||
|
||||
break
|
||||
|
||||
else:
|
||||
print(f"Fatal error ({getLineNumber()}): Impossible error")
|
||||
continue
|
||||
|
||||
finalConflictLogs = {
|
||||
"Conflicts": conflictLogs,
|
||||
"Critical": {
|
||||
"Total": criticalCount,
|
||||
"Students": studentsCritical,
|
||||
"Errors": [{
|
||||
"Total": c_mc_count,
|
||||
"Description": "Missing too many Classes",
|
||||
"Code": "C-MC"
|
||||
}, {
|
||||
"Total": c_cr_count,
|
||||
"Description": "Couldn't Resolve",
|
||||
"Code": "C-CR"
|
||||
}]
|
||||
},
|
||||
"Acceptable": {
|
||||
"Total": acceptableCount,
|
||||
"Students": studentsAcceptable,
|
||||
"Errors": [{
|
||||
"Total": a_mc_count,
|
||||
"Description": "Missing 1-2 Classes",
|
||||
"Code": "A-MC"
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
# Update Student records
|
||||
with open(studentsDir, "w") as outfile:
|
||||
json.dump(students, outfile, indent=2)
|
||||
|
||||
# Log Conflict to records
|
||||
with open(conflictsDir, "w") as outfile:
|
||||
json.dump(finalConflictLogs, outfile, indent=2)
|
||||
|
||||
return running
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("Processing...")
|
||||
|
||||
sampleStudents = getSampleStudents(True)
|
||||
samplemockCourses = getSampleCourses(True)
|
||||
timetable = {}
|
||||
timetable["Version"] = 3
|
||||
timetable["timetable"] = generateScheduleV3(sampleStudents, samplemockCourses)
|
||||
|
||||
with open("../output/timetable.json", "w") as outfile:
|
||||
json.dump(timetable, outfile, indent=2)
|
||||
|
||||
print("Done")
|
||||
@@ -1,98 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
from prettytable import PrettyTable
|
||||
from typing import Tuple
|
||||
import json
|
||||
import sys
|
||||
|
||||
# Import required utilities
|
||||
from util.mockStudents import generateMockStudents, getSampleStudents
|
||||
from util.generateCourses import getSampleCourses
|
||||
from util.courses import mockCourses
|
||||
|
||||
# Import Algorithms
|
||||
from scheduleGenerator.generator_v1 import generateScheduleV1
|
||||
from scheduleGenerator.generator_v2 import generateScheduleV2
|
||||
from scheduleGenerator.generator_v3 import generateScheduleV3
|
||||
|
||||
def errorOutput(students) -> Tuple[PrettyTable, dict, dict]:
|
||||
# Error Table calulation / output
|
||||
f = open('./output/conflicts.json')
|
||||
conflicts = json.load(f)
|
||||
f.close()
|
||||
totalCritical = conflicts["Critical"]["Students"]
|
||||
totalAcceptable = conflicts["Acceptable"]["Students"]
|
||||
|
||||
t = PrettyTable(['Type', 'Error %', 'Success %', 'Student Error Ratio'])
|
||||
|
||||
errorsC = round(totalCritical / len(students) * 100, 2)
|
||||
successC = round(100 - errorsC, 2)
|
||||
errorsA = round(totalAcceptable / len(students) * 100, 2)
|
||||
successA = round(100 - errorsA, 2)
|
||||
|
||||
t.add_row(['Critical', f"{errorsC} %", f"{successC} %", f"{totalCritical}/{len(students)} Students"])
|
||||
t.add_row(['Acceptable', f"{errorsA} %", f"{successA} %", f"{totalAcceptable}/{len(students)} Students"])
|
||||
|
||||
return t, conflicts["Critical"], conflicts["Acceptable"]
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if len(sys.argv) == 1:
|
||||
print("Missing argument")
|
||||
exit()
|
||||
|
||||
if sys.argv[1].upper() == 'V1':
|
||||
print("Processing...")
|
||||
|
||||
mockStudents = generateMockStudents(400)
|
||||
timetable = {}
|
||||
timetable["Version"] = 1
|
||||
timetable["timetable"] = generateScheduleV1(mockStudents, mockCourses)
|
||||
|
||||
elif sys.argv[1].upper() == 'V2':
|
||||
print("Processing...")
|
||||
|
||||
mockStudents = generateMockStudents(400)
|
||||
timetable = {}
|
||||
timetable["Version"] = 2
|
||||
timetable["timetable"] = generateScheduleV2(mockStudents, mockCourses)
|
||||
|
||||
|
||||
elif sys.argv[1].upper() == 'V3':
|
||||
|
||||
print("Processing...\n")
|
||||
|
||||
sampleStudents = getSampleStudents("./sample_data/course_selection_data.csv", True)
|
||||
samplemockCourses = getSampleCourses("./sample_data/course_selection_data.csv", True)
|
||||
timetable = {}
|
||||
timetable["Version"] = 3
|
||||
timetable["timetable"] = generateScheduleV3(sampleStudents, samplemockCourses, 40, "./output/students.json", "./output/conflicts.json")
|
||||
|
||||
errors, _, _ = errorOutput(sampleStudents)
|
||||
print(errors)
|
||||
|
||||
elif sys.argv[1].upper() == "ERRORS":
|
||||
f = open('./output/students.json')
|
||||
studentData = json.load(f)
|
||||
f.close()
|
||||
errors, critical, acceptable = errorOutput(studentData)
|
||||
print()
|
||||
print(errors)
|
||||
|
||||
print(f"\n{critical['Total']} critical errors")
|
||||
for i in range(len(critical["Errors"])):
|
||||
print(f"x{critical['Errors'][i]['Total']} {critical['Errors'][i]['Code']} Errors: Critical - {critical['Errors'][i]['Description']}")
|
||||
|
||||
print(f"\n{acceptable['Total']} acceptable errors")
|
||||
for i in range(len(acceptable["Errors"])):
|
||||
print(f"x{acceptable['Errors'][i]['Total']} {acceptable['Errors'][i]['Code']} Errors: Critical - {acceptable['Errors'][i]['Description']}")
|
||||
|
||||
exit()
|
||||
|
||||
else:
|
||||
print("Invalid argument")
|
||||
exit()
|
||||
|
||||
with open("./output/timetable.json", "w") as outfile:
|
||||
json.dump(timetable, outfile, indent=2)
|
||||
|
||||
print("\nDone")
|
||||
@@ -1,222 +0,0 @@
|
||||
# Fake sample data
|
||||
|
||||
mockCourses = {
|
||||
"P-CL": {
|
||||
"name": "Pre-Calculus",
|
||||
"code": "P-CL",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"CL": {
|
||||
"name": "Calculus",
|
||||
"code": "CL",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"EN-CW": {
|
||||
"name": "English: Creative Writing",
|
||||
"code": "EN-CW",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"EN-LS": {
|
||||
"name": "English: Literary Studies",
|
||||
"code": "EN-LS",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"EN-C": {
|
||||
"name": "English: Compisition",
|
||||
"code": "EN-C",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"S-J": {
|
||||
"name": "Social Justice",
|
||||
"code": "S-J",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"S-H": {
|
||||
"name": "History",
|
||||
"code": "S-H",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"S-P": {
|
||||
"name": "Psychology",
|
||||
"code": "S-P",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"SC-P": {
|
||||
"name": "Physics",
|
||||
"code": "SC-P",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"SC-B": {
|
||||
"name": "Biology",
|
||||
"code": "SC-B",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"SC-C": {
|
||||
"name": "Chemistry",
|
||||
"code": "SC-C",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"SC-ES": {
|
||||
"name": "Earth Science",
|
||||
"code": "SC-ES",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"M": {
|
||||
"name": "Music",
|
||||
"code": "M",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"CH": {
|
||||
"name": "Choir",
|
||||
"code": "CH",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"DN": {
|
||||
"name": "Dance",
|
||||
"code": "DN",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"CS": {
|
||||
"name": "Computer Science",
|
||||
"code": "CS",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"GD": {
|
||||
"name": "Game Development",
|
||||
"code": "GD",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"WW": {
|
||||
"name": "Woodwork",
|
||||
"code": "WW",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"MW": {
|
||||
"name": "MetwalWork",
|
||||
"code": "MW",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"M-WP": {
|
||||
"name": "Math: Workplace",
|
||||
"code": "M-WP",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"M-F": {
|
||||
"name": "Math: Foundations",
|
||||
"code": "M-F",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"BN": {
|
||||
"name": "Band",
|
||||
"code": "BN",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"TH": {
|
||||
"name": "Theatre",
|
||||
"code": "TH",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"VD-P": {
|
||||
"name": "Video Production",
|
||||
"code": "VD-P",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
}
|
||||
}
|
||||
|
||||
activeCourses = {}
|
||||
@@ -1,36 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import csv
|
||||
|
||||
realCourses = {}
|
||||
|
||||
# Get all courses from real sample data
|
||||
def getSampleCourses(data_dir, log=False) -> dict:
|
||||
with open(data_dir, newline='') as csvfile:
|
||||
reader = csv.DictReader(csvfile)
|
||||
for row in reader:
|
||||
exists = False
|
||||
for course in realCourses:
|
||||
exists = True if realCourses[course]["CrsNo"] == row["CrsNo"] else False
|
||||
if exists: break
|
||||
if not exists:
|
||||
realCourses[row["CrsNo"]] = {
|
||||
"CrsNo": row["CrsNo"],
|
||||
"Requests": 0,
|
||||
"Description": row["Description"],
|
||||
"Credits": 4,
|
||||
"students": []
|
||||
}
|
||||
|
||||
if log:
|
||||
with open("./output/realCourses.json", "w") as outfile:
|
||||
json.dump(realCourses, outfile, indent=2)
|
||||
|
||||
return realCourses
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
courseSet: dict = getSampleCourses("../sample_data/course_selection_data.csv")
|
||||
|
||||
with open("../output/realCourses.json", "w") as outfile:
|
||||
json.dump(courseSet, outfile, indent=2)
|
||||
@@ -1,111 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import random
|
||||
import names
|
||||
import json
|
||||
import csv
|
||||
import sys
|
||||
from util.courses import mockCourses
|
||||
|
||||
flex= ["XAT--12A-S", "XAT--12B-S"]
|
||||
|
||||
mockStudents: list[dict] = []
|
||||
|
||||
# Generate n students for mock data
|
||||
def generateMockStudents(n: int) -> list[dict]:
|
||||
for _ in range(n):
|
||||
newStudent = {
|
||||
"name": names.get_full_name(),
|
||||
"requests": [], # list of class codes
|
||||
"schedule": {
|
||||
"block1": "",
|
||||
"block2": "",
|
||||
"block3": "",
|
||||
"block4": "",
|
||||
"block5": "",
|
||||
"block6": "",
|
||||
"block7": "",
|
||||
"block8": ""
|
||||
}
|
||||
}
|
||||
# Get list of random class choices with no repeats
|
||||
# 8 primary choices, 2 secondary choices
|
||||
courseSelection = random.sample(range(0, len(mockCourses)), 10)
|
||||
for courseNum in courseSelection:
|
||||
newStudent["requests"].append(list(mockCourses)[courseNum])
|
||||
mockStudents.append(newStudent)
|
||||
|
||||
return mockStudents
|
||||
|
||||
|
||||
# sort real sample data into usable dictionary
|
||||
def getSampleStudents(data_dir: str, log: bool = False) -> list[dict]:
|
||||
with open(data_dir, newline='') as csvfile:
|
||||
reader = csv.DictReader(csvfile)
|
||||
for row in reader:
|
||||
exists = False
|
||||
for student in mockStudents:
|
||||
exists = True if student["Pupil #"] == row["Pupil #"] else False
|
||||
if exists: break
|
||||
alternate = True if row["Alternate?"] == 'TRUE' else False
|
||||
if exists:
|
||||
if len(mockStudents[student["studentIndex"]]["requests"]) >= 10 and not alternate and row["CrsNo"] not in flex: alternate = True
|
||||
mockStudents[student["studentIndex"]]["requests"].append({
|
||||
"CrsNo": row["CrsNo"],
|
||||
"Description": row["Description"],
|
||||
"alt": alternate
|
||||
})
|
||||
if row["CrsNo"] not in flex and not alternate and mockStudents[student["studentIndex"]]["expectedClasses"] < 10:
|
||||
mockStudents[student["studentIndex"]]["expectedClasses"] += 1
|
||||
else:
|
||||
newStudent = {
|
||||
"Pupil #": row["Pupil #"],
|
||||
"requests": [{
|
||||
"CrsNo": row["CrsNo"],
|
||||
"Description": row["Description"],
|
||||
"alt": alternate
|
||||
}],
|
||||
"schedule": {
|
||||
"block1": [],
|
||||
"block2": [],
|
||||
"block3": [],
|
||||
"block4": [],
|
||||
"block5": [],
|
||||
"block6": [],
|
||||
"block7": [],
|
||||
"block8": [],
|
||||
"block9": [],
|
||||
"block10": []
|
||||
},
|
||||
"expectedClasses": 1,
|
||||
"classes": 0,
|
||||
"remainingAlts": [],
|
||||
"studentIndex": len(mockStudents)
|
||||
}
|
||||
mockStudents.append(newStudent)
|
||||
|
||||
if log:
|
||||
with open("./output/students.json", "w") as outfile:
|
||||
json.dump(mockStudents, outfile, indent=2)
|
||||
|
||||
return mockStudents
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) == 1:
|
||||
print("Missing argument")
|
||||
exit()
|
||||
if sys.argv[1].lower() == 'sample':
|
||||
studentRequests: list[dict] = getSampleStudents("../sample_data/course_selection_data.csv")
|
||||
|
||||
with open("../output/students.json", "w") as outfile:
|
||||
json.dump(studentRequests, outfile, indent=2)
|
||||
elif sys.argv[1].lower() == 'mock':
|
||||
studentRequests: list[dict] = generateMockStudents(400)
|
||||
|
||||
with open("../output/students.json", "w") as outfile:
|
||||
json.dump(studentRequests, outfile, indent=2)
|
||||
else:
|
||||
print("Invalid argument")
|
||||
exit()
|
||||
|
||||
print("done")
|
||||
Reference in new issue
Block a user