I very new to Angular, and i'm working on Angular4 + PHP application, the user credentials are sent to the server from Angular app and it is validated in the PHP server (where db is MySQL). I have created the session variables in PHP, but i don't know how to use them in the Angular app in order to allow or disallow the user from accessing the dashboard, settings, etc. I'm using Service
and Guard
in this application,
Angular code:
home.component.ts
authUser(event){
let formData = new FormData();
formData.append('uname',event.target[0].value);
formData.append('pwd',event.target[1].value);
this.http.post('http://localhost/auth.php', formData)
.subscribe((data) => {
let dat = data.json();
if (dat){
this.user.setUserBase();
this.route.navigate(['report']);
}
}, (error) => {
console.log("Error!", error);
});
}
user.service.ts
@Injectable()
export class UserbaseService {
private isLoggedIn;
constructor() {
this.isLoggedIn = false;
}
setUserBase(){
this.isLoggedIn = true;
}
getUserBase(){
return (this.isLoggedIn);
}
}
app.module.ts
const appRoutes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'upload',
canActivate: [AuthGuard],
component: UploadComponent
},
]
auth.guard.ts
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.user.getUserBase();
}
PHP Code:
<?php
session_start();
header('Access-Control-Allow-Origin: *');
require('connect.php');
$username = $_POST['uname'];
$password = $_POST['pwd'];
$query = "SELECT * FROM auth WHERE uname='$username' and passwd='$password'";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if (!isset($myObj))
$myObj = new stdClass();
if ($count == 1){
$_SESSION['username'] = $username;
}
if (isset($_SESSION['username'])){
$myObj->user = $username;
$myObj->status = "authentic";
}
$response = json_encode($myObj);
echo ($response);
?>
These are the navigation I have in my App; Home
(default page), Dashboard
, Settings
, Logout
.
I want the user to be redirected to Dashboard
from Home
if the session is active and if session is not destroyed then user should be redirected to Home
from Dashboard
, or Settings
and also i want to destroy the session by clicking Logout
. Help will be appreciated.