Skip to content
This repository has been archived by the owner on Mar 10, 2024. It is now read-only.

Commit

Permalink
Merge pull request #12 from nitrotap/feature/login-api
Browse files Browse the repository at this point in the history
adding login and signup auth system
  • Loading branch information
nitrotap authored Jun 7, 2023
2 parents 7e4e8ad + 8aa7259 commit 98c38db
Show file tree
Hide file tree
Showing 11 changed files with 299 additions and 45 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# User added ignores
env.php

scratch.*
scratch/
# Logs
logs
*.log
Expand Down
1 change: 0 additions & 1 deletion client/src/app/login/login.page.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
</ion-toolbar>
</ion-header>


<ion-content [fullscreen]="true">
<app-nav></app-nav>
<div style="display: flex; justify-content: center; align-items: center; ">
Expand Down
75 changes: 69 additions & 6 deletions client/src/app/login/login.page.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserDataService } from '../services/user-data.service';
import { ToastController } from '@ionic/angular';


@Component({
Expand All @@ -12,15 +14,51 @@ export class LoginPage implements OnInit {
password: any;
errorMessage: any;

constructor(private router: Router) { }
constructor(private router: Router, private userDataService: UserDataService, private toastController: ToastController) { }

login() {
if (this.email && this.password) {
// You can implement your own login logic here
// For simplicity, we'll just navigate to a welcome page
this.router.navigateByUrl('/home');

const result = this.validateAndSanitizeEmailAndPassword(this.email, this.password);

if (result.isValid) {
let formData = {
"email": result.sanitizedEmail,
"password": result.sanitizedPassword
}

this.userDataService.login(formData).subscribe({
next: async (response: any) => {
console.log('Response from server:', response)
const alert = await this.toastController.create({
message: 'Successfully logged into your account!',
duration: 2000,
position: 'bottom',
color: 'success'
});
await alert.present();

// set session variables in client
sessionStorage.setItem("sessionID", response.sessionID);
sessionStorage.setItem("access", response.Authorization);

// this.router.navigateByUrl('/login');
},
error: async (error) => {
console.error('Error:', error)
const alert = await this.toastController.create({
message: error,
duration: 2000,
position: 'bottom',
color: 'danger'
});
await alert.present();

}
});

} else {
this.errorMessage = 'Please enter your email and password.';
this.errorMessage = 'Something has gone wrong. Please try again.';

}
}

Expand All @@ -34,4 +72,29 @@ export class LoginPage implements OnInit {
ngOnInit() {
}

validateAndSanitizeEmailAndPassword(email: string, password: string): { isValid: boolean, sanitizedEmail: string, sanitizedPassword: string } {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// Check if email is valid
if (!emailRegex.test(email)) {
this.errorMessage = "Email is not valid. Please try again."
return { isValid: false, sanitizedEmail: '', sanitizedPassword: '' };
}

// Remove leading/trailing white spaces from email
const sanitizedEmail = email.trim();

// Sanitize password by removing leading/trailing white spaces
const sanitizedPassword = password.trim();

// Check if password meets certain requirements (e.g., minimum length)
if (sanitizedPassword.length < 8) {
this.errorMessage = "Password requirements not met. Please try again."
return { isValid: false, sanitizedEmail, sanitizedPassword: '' };
}

// If all validations pass, return valid and sanitized values
return { isValid: true, sanitizedEmail, sanitizedPassword };
}

}
35 changes: 31 additions & 4 deletions client/src/app/services/user-data.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,21 +85,48 @@ export class UserDataService {

}

login(formData: any) {
const loginURL = `${this.url}auth/`;

const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
}),
params: new HttpParams(),
};

// Convert the formData object to URL-encoded format
let body = new HttpParams();
for (const key of Object.keys(formData)) {
body = body.set(key, formData[key]);
}

return this.http.post(loginURL, body.toString(), httpOptions);

}




// Start a session
startSession() {
return this.http.get('http://localhost/brain-lift/server/api/user/start_session.php');
const startSessionURL = `${this.url}/start_session.php`;

return this.http.get(startSessionURL);

}

// Store session data
storeSessionData(data: any) {
return this.http.post('http://localhost/brain-lift/server/api/user/store_session_data.php', data);
storeSessionData() {
console.log()


}


// Retrieve session data
getSessionData() {
return this.http.get('http://localhost/brain-lift/server/api/user/get_session_data.php');
const getSessionDataURL = `${this.url}/get_session_data.php`;
return this.http.get(getSessionDataURL);
}
}
8 changes: 4 additions & 4 deletions client/src/app/signup/signup.page.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@
<ion-card style="width: 80vw;">

<ion-item>
<ion-label position="floating">Email (Username)</ion-label>
<ion-input [(ngModel)]="email"></ion-input>
<ion-label position="floating">Email</ion-label>
<ion-input [(ngModel)]="email" aria-required="true"></ion-input>
</ion-item>

<ion-item>
<ion-label position="floating">Password</ion-label>
<ion-input [(ngModel)]="password" type="password"></ion-input>
<ion-input [(ngModel)]="password" type="password" aria-required="true"></ion-input>
</ion-item>

<ion-button expand="full" (click)="signup()">Sign Up</ion-button>
<ion-button expand="full" (click)="signup(email, password)">Sign Up</ion-button>
<p>{{ errorMessage }}</p>
</ion-card>

Expand Down
82 changes: 75 additions & 7 deletions client/src/app/signup/signup.page.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserDataService } from '../services/user-data.service';
import { ActionSheetController, AlertController, ToastController } from '@ionic/angular';


@Component({
selector: 'app-signup',
Expand All @@ -12,20 +15,85 @@ export class SignupPage implements OnInit {
errorMessage: any;


constructor(private router: Router) { }
constructor(private router: Router, private userDataService: UserDataService, private toastController: ToastController) { }

signup(email: string, password: string) {

const result = this.validateAndSanitizeEmailAndPassword(email, password);

if (result.isValid) {
let formData = {
"email": result.sanitizedEmail,
"password": result.sanitizedPassword
}

this.userDataService.postData(formData).subscribe({
next: async (response) => {
console.log('Response from server:', response)
const alert = await this.toastController.create({
message: 'Successfully created your account!',
duration: 2000,
position: 'bottom',
color: 'success'
});
await alert.present();

// set session variables in client
sessionStorage.setItem("sessionID", response.sessionID);
sessionStorage.setItem("access", response.Authorization);

// this.router.navigateByUrl('/login');
},
error: async (error) => {
console.error('Error:', error)
const alert = await this.toastController.create({
message: error,
duration: 2000,
position: 'bottom',
color: 'danger'
});
await alert.present();

}
});

signup() {
if (this.email && this.password) {
// You can implement your own signup logic here
// For simplicity, we'll just navigate to the login page
this.router.navigateByUrl('/login');
} else {
this.errorMessage = 'Please enter an email and password.';
this.errorMessage = 'Something has gone wrong. Please try again.';

}


}




ngOnInit() {
}

validateAndSanitizeEmailAndPassword(email: string, password: string): { isValid: boolean, sanitizedEmail: string, sanitizedPassword: string } {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// Check if email is valid
if (!emailRegex.test(email)) {
this.errorMessage = "Email is not valid. Please try again."
return { isValid: false, sanitizedEmail: '', sanitizedPassword: '' };
}

// Remove leading/trailing white spaces from email
const sanitizedEmail = email.trim();

// Sanitize password by removing leading/trailing white spaces
const sanitizedPassword = password.trim();

// Check if password meets certain requirements (e.g., minimum length)
if (sanitizedPassword.length < 8) {
this.errorMessage = "Password requirements not met. Please try again."
return { isValid: false, sanitizedEmail, sanitizedPassword: '' };
}

// If all validations pass, return valid and sanitized values
return { isValid: true, sanitizedEmail, sanitizedPassword };
}

}
3 changes: 1 addition & 2 deletions client/src/app/test/test.page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,7 @@ export class TestPage implements OnInit {
}

storeData() {
const data = { name: 'John Doe' };
this.userDataService.storeSessionData(data).subscribe();
this.userDataService.storeSessionData();
}

getData() {
Expand Down
30 changes: 13 additions & 17 deletions server/api/task/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,21 @@
}

// API endpoint for retrieving data from a table
// Check if request method is GET
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// Retrieve data from the table
// Prepare and execute a query to select all data from the table
$query = "SELECT * FROM $table";
$stmt = $db->prepare($query);
$stmt->execute();
// Fetch all data from the statement as associative array

$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Return the data as JSON response
// Set headers to return a JSON response

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *'); // Allow requests from any origin
// Output the data as a JSON
try {
// Retrieve data from the table
$query = "SELECT * FROM $table";
$stmt = $db->prepare($query);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($data);
// Return the data as JSON response
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *'); // Allow requests from any origin
echo json_encode($data);
} catch (PDOException $e) {
die("Retrieval failed: " . $e->getMessage());
}
}

// API endpoint for inserting data into a table
Expand Down
Loading

0 comments on commit 98c38db

Please sign in to comment.