JavaScript — Как подключить базу данных для этого углового кода входа

** У меня есть код для входа в систему. Я жестко кодирую логин и пароль.
Теперь я должен подключиться к базе данных с помощью php. Где я должен создать этот метод GET или POST. Мне нужно создать этот сервисный файл метода get или post или файл контроллера. как объединить с этим кодом для этого файла.

Я делаю файл с помощью php. **

service.js

'use strict';angular.module('Authentication')

.factory('AuthenticationService',
['Base64', '$http', '$cookieStore', '$rootScope', '$timeout',
function (Base64, $http, $cookieStore, $rootScope, $timeout) {
var service = {};

service.Login = function (username, password, callback) {

/* Dummy authentication for testing, uses $timeout to simulate api call
----------------------------------------------*/

$timeout(function(){
var response = { success: username === 'test' && password === 'test' };
if(!response.success) {
response.message = 'Username or password is incorrect';
}
callback(response);
}, 1000);/* Use this for real authentication
----------------------------------------------*/
//$http.post('/api/authenticate', { username: username, password: password })
//    .success(function (response) {
//        callback(response);
//    });

};

service.SetCredentials = function (username, password) {
var authdata = Base64.encode(username + ':' + password);

$rootScope.globals = {
currentUser: {
username: username,
authdata: authdata
}
};

$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; // jshint ignore:line
$cookieStore.put('globals', $rootScope.globals);
};

service.ClearCredentials = function () {
$rootScope.globals = {};
$cookieStore.remove('globals');
$http.defaults.headers.common.Authorization = 'Basic ';
};

return service;
}]).factory('Base64', function () {
/* jshint ignore:start */var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

return {
encode: function (input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;

do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);

enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;

if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}

output = output +
keyStr.charAt(enc1) +
keyStr.charAt(enc2) +
keyStr.charAt(enc3) +
keyStr.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);

return output;
},

decode: function (input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;

// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
window.alert("There were invalid base64 characters in the input text.\n" +
"Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
"Expect errors in decoding.");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

do {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));

chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;

output = output + String.fromCharCode(chr1);

if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}

chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";

} while (i < input.length);

return output;
}
};

/* jshint ignore:end */
});

controller.js

'use strict';angular.module('Authentication')

.controller('LoginController',
['$scope', '$rootScope', '$location', 'AuthenticationService',
function ($scope, $rootScope, $location, AuthenticationService) {
// reset login status
AuthenticationService.ClearCredentials();

$scope.login = function () {
$scope.dataLoading = true;
AuthenticationService.Login($scope.username, $scope.password, function(response) {
if(response.success) {
AuthenticationService.SetCredentials($scope.username, $scope.password);
$location.path('/');
} else {
$scope.error = response.message;
$scope.dataLoading = false;
}
});
};
}]);

1

Решение

для локальной базы данных

1. Создайте свои php-файлы, такие как Api.php, .htaccess, rest.in.php, во флопдере с именем YourFolder в вашем local.i.e с в HTDOCS

2. сейчас в ваших услугах.js

объявите своего хоста как ниже

var hostname = "localhost:/yourfolder";

затем создайте сервисную базу для звонков по вашему php-коду, как показано ниже

var serviceBase = 'http://'+hostname+'/api.php';

Теперь внутри вашего метода входа в service.js вызовите метод php, который выполняет ваш вход в систему для внутреннего процесса

 function Login(data) {
$http.post(serviceBase+"?action=doLogin",data)
.success(function (response) {
callback(response, true);

})
.error(function(error){
callback(error, false);
})
}

3. Теперь это вызовет ваш php-файл и запустит метод doLogin. Поэтому вам нужно настроить базу данных в вашем php-файле.

Api.php

<?php

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

require_once("Rest.inc.php");

class API extends REST {

public $data = "";

const DB_SERVER = "localhost";
const DB_USER = ""; your DB username
const DB_PASSWORD = ""; your DB password
const DB = "";your DB name

private $db = NULL;
private $mysqli = NULL;
public function __construct(){
parent::__construct();              // Init parent contructor
$this->dbConnect();                 // Initiate Database connection
}

/*
*  Connect to Database
*/
private function dbConnect(){
$this->mysqli = new mysqli(self::DB_SERVER, self::DB_USER, self::DB_PASSWORD, self::DB);
}

/*
* Dynmically call the method based on the query string
*/
public function processApi(){
$func = strtolower(trim(str_replace("/","",$_REQUEST['action'])));

if((int)method_exists($this,$func) > 0) {
$this->$func();
} else
$this->response('',404); // If the method not exist with in this class "Page not found".
}
/**
* if post data email and password is correct then,
* it will send the user object as return.
* else post data is wrong send the error report.
*/

private function Dologin(){
//wirte your php code here to send data to db

}}

$api = new API;
$api->processApi();

?>

Rest.inc.php

<?php

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

class REST {

public $_allow = array();
public $_content_type = "application/json";
public $_request = array();

private $_method = "";
private $_code = 200;

public function __construct(){
$this->inputs();
}

public function get_referer(){
return $_SERVER['HTTP_REFERER'];
}

public function response($data,$status){

$this->_code = ($status)?$status:200;
$this->set_headers();
echo $data;
exit;
}
// For a list of http codes checkout http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
private function get_status_message(){

$status = array(
200 => 'OK',
201 => 'Created',
204 => 'No Content',
400 => 'validations',
404 => 'Not Found',
406 => 'Not Acceptable');
error_log(($status[$this->_code])?$status[$this->_code]:$status[500]);
return ($status[$this->_code])?$status[$this->_code]:$status[500];
}

public function get_request_method(){
return $_SERVER['REQUEST_METHOD'];
}

private function inputs(){
switch($this->get_request_method()){
case "POST":
$this->_request = $this->cleanInputs($_POST);
break;
case "GET":
case "DELETE":
$this->_request = $this->cleanInputs($_GET);
break;
case "PUT":
parse_str(file_get_contents("php://input"),$this->_request);
$this->_request = $this->cleanInputs($this->_request);
break;
default:
$this->response('',406);
break;
}
}

private function cleanInputs($data){
$clean_input = array();
if(is_array($data)){
foreach($data as $k => $v){
$clean_input[$k] = $this->cleanInputs($v);
}
} else {
if(get_magic_quotes_gpc()){
$data = trim(stripslashes($data));
}
$data = strip_tags($data);
$clean_input = trim($data);
}
return $clean_input;
}

private function set_headers(){
header("HTTP/1.1 ".$this->_code." ".$this->get_status_message());
header("Content-Type:".$this->_content_type);
}
}
?>
0

Другие решения

Других решений пока нет …