Skip to content
This repository was archived by the owner on Mar 10, 2024. It is now read-only.
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
env.php
scratch.*
scratch/
vendor/
# Logs
logs
*.log
Expand Down
2 changes: 2 additions & 0 deletions client/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ log.txt
/www
/platforms
/plugins
/android
/ios

# Compiled output
/dist
Expand Down
6 changes: 6 additions & 0 deletions client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@capacitor/status-bar": "5.0.2",
"@ionic/angular": "^7.0.0",
"ionicons": "^7.0.0",
"jwt-decode": "^3.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.13.0"
Expand Down
10 changes: 8 additions & 2 deletions client/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,17 @@ import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { HttpClientModule } from '@angular/common/http';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { JWTInterceptor } from './jwtinterceptor.interceptor';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule],
providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
providers: [
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
{ provide: HTTP_INTERCEPTORS, useClass: JWTInterceptor, multi: true },

],
bootstrap: [AppComponent],
})
export class AppModule { }
16 changes: 16 additions & 0 deletions client/src/app/jwtinterceptor.interceptor.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';

import { JWTInterceptorInterceptor } from './jwtinterceptor.interceptor';

describe('JWTInterceptorInterceptor', () => {
beforeEach(() => TestBed.configureTestingModule({
providers: [
JWTInterceptorInterceptor
]
}));

it('should be created', () => {
const interceptor: JWTInterceptorInterceptor = TestBed.inject(JWTInterceptorInterceptor);
expect(interceptor).toBeTruthy();
});
});
24 changes: 24 additions & 0 deletions client/src/app/jwtinterceptor.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class JWTInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const jwt = sessionStorage.getItem('JWT'); // Assuming JWT is stored in sessionStorage

if (jwt) {
const cloned = req.clone({
setHeaders: {
Authorization: `Bearer ${jwt}`,
},
});

console.log(cloned);

return next.handle(cloned);
} else {
return next.handle(req);
}
}
}
20 changes: 19 additions & 1 deletion client/src/app/services/user-data.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ import { Router } from '@angular/router';
providedIn: 'root'
})
export class UserDataService {
private url = 'https://www.brain-lift.org/brain-lift/server/api/user/';
// private url = 'https://www.brain-lift.org/brain-lift/server/api/user/';

private url = 'http://localhost/brain-lift/server/api/user/';

constructor(private http: HttpClient, private router: Router) { }

Expand Down Expand Up @@ -105,6 +106,14 @@ export class UserDataService {

}

authenticate(username: string, password: string) {
const loginURL = `${this.url}auth/`;

this.http.post<{ token: string }>(loginURL, { username, password })
.subscribe(res => {
localStorage.setItem('JWT', res.token);
});
}



Expand All @@ -121,6 +130,7 @@ export class UserDataService {
console.log()



}


Expand All @@ -129,4 +139,12 @@ export class UserDataService {
const getSessionDataURL = `${this.url}/get_session_data.php`;
return this.http.get(getSessionDataURL);
}

getJWT() {
const url = 'http://localhost/brain-lift/server/api/user/';
const jwtURL = `${url}auth/jwt-encode.php`;
return this.http.get(jwtURL)
}


}
8 changes: 6 additions & 2 deletions client/src/app/test/test.page.html
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,18 @@
<ion-button expand="full" color="primary" class="get-started-button" (click)="startSession()">
Start Session Data
</ion-button>
<ion-button expand="full" color="primary" class="get-started-button" (click)="storeData()">
<ion-button expand="full" color="primary" class="get-started-button" (click)="storeSessionData()">
Store Session Data
</ion-button>
<ion-button expand="full" color="primary" class="get-started-button" (click)="getData()">
<ion-button expand="full" color="primary" class="get-started-button" (click)="getSessionData()">
Get Session Data</ion-button>



<ion-title>JWT Data</ion-title>
<ion-button expand="full" color="primary" class="get-started-button" (click)="getAndDecodeJWT()">
Get JWT</ion-button>
{{jwt}}



Expand Down
22 changes: 20 additions & 2 deletions client/src/app/test/test.page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { Component, OnInit } from '@angular/core';
import { TaskDataService } from '../services/task-data.service';
import { AnswerDataService } from '../services/answer-data.service';
import { UserDataService } from '../services/user-data.service';
import jwt_decode, { JwtPayload } from 'jwt-decode'
import jwtDecode from 'jwt-decode';

@Component({
selector: 'app-test',
Expand Down Expand Up @@ -207,17 +209,33 @@ export class TestPage implements OnInit {
});
}

storeData() {
storeSessionData() {
this.userDataService.storeSessionData();
}

getData() {
getSessionData() {
this.userDataService.getSessionData().subscribe((data) => {
console.log(data);
});
}


jwt: any;
getAndDecodeJWT() {
this.userDataService.getJWT().subscribe((data) => {
this.jwt = data;
const token: string = data.toString();
sessionStorage.setItem('JWT', JSON.stringify(data));

const decoded = jwtDecode<JwtPayload>(token); // Returns with the JwtPayload type
this.jwt = JSON.stringify(decoded);



})
}





Expand Down
65 changes: 65 additions & 0 deletions server/api/task/new/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php
// Check if request method is OPTIONS
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
// Respond to preflight request
header('Access-Control-Allow-Origin: *'); // Allow requests from any origin
header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); // Allow these methods
header('Access-Control-Allow-Headers: Content-Type'); // Allow this header
header('Content-Type: application/json');
exit(0); // No further processing if OPTIONS request
}


// Includes environment variables and sanitize function from specified files
include(__DIR__ . '../../../env.php');
include(__DIR__ . '../../../sanitize.php');

// Specify table
$table = 'task';

// Establish a connection to the database
try {
$db = new PDO("mysql:host=$host;dbname=$dbName", $username, $password);
// If connection is successful, set the error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
// If connection fails, stop the script and show an error message
die("Database connection failed: " . $e->getMessage());
}

// API endpoint for inserting data into a table
// Check if request method is POST

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

// Sanitize input data

sanitizeRequestStrings();
$requestData = $_REQUEST;
// Check if required data is provided
if (isset($requestData['taskName']) && isset($requestData['taskType']) && isset($requestData['taskTime']) && isset($requestData['userID'])) {

// Insert the data into the table
// Prepare and bind parameters for an insert query

$query = "INSERT INTO $table (taskName, taskType, taskTime, userID) VALUES (:value1, :value2, :value3, :value4)";
$stmt = $db->prepare($query);
$stmt->bindParam(':value1', $requestData['taskName']);
$stmt->bindParam(':value2', $requestData['taskType']);
$stmt->bindParam(':value3', $requestData['taskTime']);
$stmt->bindParam(':value4', $requestData['userID']);

$stmt->execute();

// Set headers to return a JSON response
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *'); // Allow requests from any origin
// Return success response
echo json_encode(array('message' => 'Data inserted successfully'));
} else {
// Return error message if required data is not provided
header('HTTP/1.1 400 Bad Request');
header('Access-Control-Allow-Origin: *'); // Allow requests from any origin
echo json_encode(array('message' => 'Required data not provided'));
}
}
Loading