Angular login using php and mysql

Lets create a login page in angular which gets the login data form a database.

If you don't want to code you can get the all from github at "https://github.com/Kimbugwerogers/angular-login"

    First create an angular project and give it a name of your desire and in the [app.module.ts] in the imports section,
 import: [   BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule,
     ReactiveFormsModule
  ],

In the [app.component.ts] feed in the following infor
export class AppComponent {
  title = 'free-am';
  loginbtn: boolean;
  logoutbtn: boolean;
  constructor(private dataService: DataserviceService) {
    dataService.getLoggedInName.subscribe(name => this.changeName(name));
    if (this.dataService.isLoggedIn())
    {
      console.log('loggedin');
      this.loginbtn = false;
      this.logoutbtn = true;
    }
    else{
     this.loginbtn = true;
     this.logoutbtn = false;
    }
}

private changeName(name: boolean): void {
  this.logoutbtn = name;
  this.loginbtn = !name;
}
logout()
{
  this.dataService.deleteToken();
  window.location.href = window.location.href;
}
}


And in [app.compoennt.html] pasta in 
<nav class="navbar navbar-expand-lg navbar-light bg-light rounded">
  <a class="navbar-brand" routerLink="home" routerLinkActive="active">M Tutorial</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample09" aria-controls="navbarsExample09" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarsExample09">
    <ul class="navbar-nav mr-auto">

        <li class="nav-item">
            <a class="nav-link" *ngIf="loginbtn" routerLink="login" routerLinkActive="active">Login</a>
          </li>
          <li class="nav-item">
            <button type="button" *ngIf="logoutbtn" class="btn btn-danger btn-block" (click)="logout()">logout</button>
          </li>
          <li class="nav-item">
            <a class="nav-link" *ngIf="loginbtn" routerLink="registration" routerLinkActive="active">Registration</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" *ngIf="logoutbtn" routerLink="dashboard" routerLinkActive="active">Product</a>
          </li>


    </ul>

  </div>
</nav>

<router-outlet></router-outlet>

And in [app.routing.module.ts] pasta 
const routes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'login', component: LoginComponent },
  { path: 'registration', component: RegistrationComponent },
  { path: 'product', loadChildren: () => import('./product/product.module').then(m => m.ProductModule), canActivate: [AuthguardGuard] },
];

Create a folder call it user and create [usermodule.ts] in that folder and pasta
export class Usermodule {
  public Idnumber;
  public namestring;
  public pwdstring;
  public emailstring;
  public mobilestring;

  constructor(Idnumbernamestringpwdstringemailstringmobilestring
{
    this.Id = Id;
    this.name = name;
    this.pwd = pwd;
    this.email = email;
    this.mobile = mobile;
  }
}

Create a registration component in [ registration.component.ts] pasta 
export class RegistrationComponent implements OnInit {
  angFormFormGroup;
  constructor(private fbFormBuilder
            private dataServiceDataserviceService
            private routerRouter) {

    this.angForm = this.fb.group({
      email: ['', [Validators.requiredValidators.minLength(1), Validators.email]],
      password: [''Validators.required],
      name: [''Validators.required],
      mobile: [''Validators.required]

    });
   }

  ngOnInit() {
  }
  postdata(angForm1)
  {
    this.dataService.userregistration(angForm1.value.name
                        angForm1.value.email
                        angForm1.value.passwordangForm1.value.mobile)
      .pipe(first())
      .subscribe(
          data => {
              this.router.navigate(['login']);
          },
          error => {
          });
  }
  get email() { return this.angForm.get('email'); }
  get password() { return this.angForm.get('password'); }
  get name() { return this.angForm.get('name'); }
  get mobile() { return this.angForm.get('mobile'); }
}


And in [registration.component.html] pasta 
<h2 class="text-center">Registration</h2>
<div class="row">
    <div class="col-md-3">
    </div>
    <div class="col-md-6 col-md-offset-3">
        <div class="jumbotron">
            <form [formGroup]="angForm" (ngSubmit)="postdata(angForm)" 
                    autocomplete="off" >
                <div class="form-group">
                    <label for="name">User Name</label>
                    <input type="text" name="name" formControlName="name" 
                            autocomplete="off" class="form-control input-sm" 
                            placeholder="User Name">

                </div>

                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="email" name="email" 
                                formControlName="email" autocomplete="off" 
                                    class="form-control input-sm" 
                                     placeholder="Email Address">

                </div>
                <div class="form-group">
                    <label for="Password">Password</label>
                    <input type="password" name="Password" 
                                formControlName="password"  
                                autocomplete="off" class="form-control input-sm" 
                                placeholder="Password">

                </div>
                <div class="form-group">
                    <label for="name">Mobile No</label>
                    <input type="text" name="mobile" 
                            formControlName="mobile" 
                            autocomplete="off" class="form-control input-sm" 
                             placeholder="Mobile No">

                </div>
                <button type="submit" class="btn btn-primary" 
                [disabled]="!angForm.valid">Registration</button>
            </form>
        </div>
    </div>
    <div class="col-md-3">
    </div>

</div>

Still in the user folder create [login.component.ts]
export class LoginComponent implements OnInit {

  angFormFormGroup;
  constructor(private fbFormBuilder
    private dataServiceDataserviceService
    private routerRouter) {
    this.angForm = this.fb.group({

      email: ['', [Validators.required
    Validators.minLength(1), Validators.email]],
      password: [''Validators.required]

    });
   }

  ngOnInit() {
  }
  postdata(angForm1)
  {
    this.dataService.userlogin(angForm1.value.emailangForm1.value.password)
      .pipe(first())
      .subscribe(
          data => {
                const redirect = 
                    this.dataService.redirectUrl ? 
                this.dataService.redirectUrl : '/product';
                this.router.navigate([redirect]);

          },
          error => {
              alert('User name or password is incorrect');
          });
  }
  get email() { return this.angForm.get('email'); }
  get password() { return this.angForm.get('password'); }
}

And in [login.component.html]

<h2 class="text-center">Login</h2>
<div class="row">
    <div class="col-md-3">
    </div>
    <div class="col-md-6 col-md-offset-3">
        <div class="jumbotron">
            <form [formGroup]="angForm" (ngSubmit)="postdata(angForm)" 
                    autocomplete="off" >
                <div class="form-group">
                    <label for="email">User Name</label>
                    <input type="email" name="email" formControlName="email" 
        autocomplete="off" class="form-control input-sm" placeholder="Email Address">

                </div>
                <div class="form-group">
                    <label for="Password">Password</label>
                    <input type="password" name="Password" 
            formControlName="password"  autocomplete="off" 
            class="form-control input-sm" placeholder="Password">

                </div>
                <button type="submit" class="btn btn-primary" 
                [disabled]="!angForm.valid">Login</button>
            </form>
        </div>
    </div>
    <div class="col-md-3">
    </div>

</div>

Create a service still in the user folder [dataservice.ts]
import { InjectableOutputEventEmitter } from '@angular/core';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataserviceService {
  redirectUrlstring;

  baseUrl = 'http://localhost/tests/login-test';
@Output() getLoggedInNameEventEmitter<any> = new EventEmitter();

  constructor(private httpClientHttpClient) {}

  public userlogin(usernamepassword) {
    return this.httpClient.post<any>(this.baseUrl + '/login.php'
    usernamepassword })
    .pipe(map(Usermodule => {
        this.setToken(Usermodule[0].name);
        this.getLoggedInName.emit(true);
        return Usermodule;
    }));
   }

   public userregistration(nameemailpwdmobile) {
    return this.httpClient.post<any>(this.baseUrl + '/registration.php'
    nameemailpwdmobile })
        .pipe(map(Usermodule => {
            return Usermodule;
        }));
  }

  // token
  setToken(tokenstring) {
    localStorage.setItem('token'token);
  }

  getToken() {
    return localStorage.getItem('token');
  }

  deleteToken() {
    localStorage.removeItem('token');
  }

  isLoggedIn() {
    const usertoken = this.getToken();
    if (usertoken != null) {
      return true;
    }
    return false;
  }

}

And [authguard.guard.ts] in the user folder
import { Injectable } from '@angular/core';
import { CanActivateActivatedRouteSnapshot
RouterStateSnapshotUrlTreeRouter } from '@angular/router';
import { Observable } from 'rxjs';
import { DataserviceService } from './dataservice.service';

@Injectable({
  providedIn: 'root'
})
export class AuthguardGuard implements CanActivate {

  constructor(private dataServiceDataserviceServiceprivate routerRouter  ) {}

  canActivate(
    routeActivatedRouteSnapshot,
    stateRouterStateSnapshot): Observable<boolean | UrlTree> | 
Promise<boolean | UrlTree> | boolean | UrlTree {

      const routeurlstring = state.url;
      return this.isLogin(routeurl);
  }

  isLogin(routeurlstring) {
    if (this.dataService.isLoggedIn()) {
      return true;
    }
    this.dataService.redirectUrl = routeurl;
    this.router.navigate(['/login'], {queryParams: { returnUrl: routeurl }} );
  }

}

If you remember there is a lazily loaded module we create called product 
this is the code for lazy loading "ng g m product --route product --module app.module"
So that will be your home page

In the dataservice we are loading  baseUrl = 'http://localhost/tests/login-test';  These are php files that connect to the database. These files are in htdocs/tests/login-test folders on my local machmachine. so make sure this url ponits to where you have located your php files
Why i highlighted htdocs is coz this is an xamp folder. so i am usig xamp for my php  

And the files are;
[config.php]
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
 
  $db_username = 'root';
 $db_password = 'put the password of your db';
 $db_name = 'loginsystems';
 $db_host = 'localhost:3306'; // if your using xamp no need of adding 3306
      
$mysqli = new mysqli($db_host$db_username$db_password,$db_name);
 
if ($mysqli->connect_error) {
    die('Error : ('$mysqli->connect_errno .') '$mysqli->connect_error);
}

[login.php]
<?php
include_once("config.php");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
if(isset($postdata) && !empty($postdata))
{
  $pwd = mysqli_real_escape_string($mysqlitrim($request->password));
   $email = mysqli_real_escape_string($mysqlitrim($request->username));
$sql='';
  $sql = "SELECT * FROM employee where email='$emailand pwd='$pwd'";
if($result = mysqli_query($mysqli,$sql))
{
 $rows = array();
  while($row = mysqli_fetch_assoc($result))
  {
    $rows[] = $row;
  }
 
  echo json_encode($rows);
}
else
{
  http_response_code(404);
}
}

And [registration.php]
<?php
include_once("config.php");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
if(isset($postdata) && !empty($postdata))
{
  $name = mysqli_real_escape_string($mysqlitrim($request->name));
  $pwd = mysqli_real_escape_string($mysqli, (int)$request->pwd);
   $email = mysqli_real_escape_string($mysqlitrim($request->email));
  $mobile = mysqli_real_escape_string($mysqli, (int)$request->mobile);
  $sql = "INSERT INTO employee(name,pwd,email,mobile) VALUES ('{$name}','{$pwd}','{$email}','{$mobile}')";
 // echo $sql;
if ($mysqli->query($sql) === TRUE) {
 
 
    $authdata = [
      'name' => $name,
    'pwd' => '',
    'email' => $email,
      'mobile' => $mobile,
      'Id'    => mysqli_insert_id($mysqli)
    ];
    echo json_encode($authdata);
 
}
}

In our datadatabase manager whichever your using maybe xamp or mysql workbench go in and create a database named loginsystems  and create a table with this data in
CREATE TABLE `employee` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `pwd` varchar(100) NOT NULL,
  `email` varchar(60) DEFAULT NULL,
  `mobile` varchar(100) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 


If you have any errors you have seen or ideas you adding plz leave a comcomment 

Comments

Popular posts from this blog

AC Light switch using relay

Mosfet and capacitor switch

Blinking LED