@dumorim wrote:
I can not log into my backend
services.js angular.module('starter') .service('AuthService', function($q, $http, USER_ROLES) { var LOCAL_TOKEN_KEY = 'yourTokenKey'; var username = ''; var isAuthenticated = false; var role = ''; var authToken; function loadUserCredentials() { var token = window.localStorage.getItem(LOCAL_TOKEN_KEY); if (token) { useCredentials(token); } } function storeUserCredentials(token) { window.localStorage.setItem(LOCAL_TOKEN_KEY, token); useCredentials(token); } function useCredentials(token) { username = token.split('.')[0]; isAuthenticated = true; authToken = token; if (username == 'admin') { role = USER_ROLES.admin } if (username == 'user') { role = USER_ROLES.public } // Set the token as header for your requests! $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; } function destroyUserCredentials() { authToken = undefined; username = ''; isAuthenticated = false; $http.defaults.headers.common['Authorization'] = undefined; window.localStorage.removeItem(LOCAL_TOKEN_KEY); } var login = function(name, pw) { return $q(function(resolve, reject) { $http.post('http://192.168.0.19/android/RespuestaJSON/login.php?callback=JSON_CALLBACK', {username:name, password:pw}). success(function(data, status, headers, config) { storeUserCredentials(data.token); resolve('Login success.'); // this callback will be called asynchronously // when the response is available }). error(function(data, status, headers, config) { reject('Login Failed.'); // called asynchronously if an error occurs // or server returns response with an error status. }); }); }; var logout = function() { destroyUserCredentials(); }; var isAuthorized = function(authorizedRoles) { if (!angular.isArray(authorizedRoles)) { authorizedRoles = [authorizedRoles]; } return (isAuthenticated && authorizedRoles.indexOf(role) !== -1); }; loadUserCredentials(); return { login: login, logout: logout, isAuthorized: isAuthorized, isAuthenticated: function() {return isAuthenticated;}, username: function() {return username;}, role: function() {return role;} }; }) .factory('AuthInterceptor', function ($rootScope, $q, AUTH_EVENTS) { return { responseError: function (response) { $rootScope.$broadcast({ 400: AUTH_EVENTS.notAuthenticated, 401: AUTH_EVENTS.notAuthenticated, 403: AUTH_EVENTS.notAuthorized }[response.status], response); return $q.reject(response); } }; }) .config(function ($httpProvider) { $httpProvider.interceptors.push('AuthInterceptor'); });
[code] //app.js
angular.module('starter', ['ionic', 'starter.controllers'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
}).config(function($stateProvider, $urlRouterProvider) {
$stateProvider//dashboard page
.state('app', {
url: "/",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})// login
.state('app.login', {
url: "app/login",
views: {
'menuContent': {
templateUrl: "templates/login.html",
controller: 'LoginCtrl'
}
}
})//dashboard pages controller .state('app.dashboard', { url: "app/dashboard", views: { 'menuContent': { templateUrl: "templates/dashboard.html", controller: 'PlaylistsCtrl' } } })
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/dashboard');
})
.run(function ($rootScope, $state, AuthService, AUTH_EVENTS) {
$rootScope.$on('$stateChangeStart', function (event,next, nextParams, fromState) {if ('data' in next && 'authorizedRoles' in next.data) { var authorizedRoles = next.data.authorizedRoles; if (!AuthService.isAuthorized(authorizedRoles)) { event.preventDefault(); $state.go($state.current, {}, {reload: true}); $rootScope.$broadcast(AUTH_EVENTS.notAuthorized); } } if (!AuthService.isAuthenticated()) { if (next.name !== 'app.login') { event.preventDefault(); $state.go('app.login'); } }
});
});[ /code][code]
constants.js
angular.module('starter')
.constant('AUTH_EVENTS', {
notAuthenticated: 'auth-not-authenticated',
notAuthorized: 'auth-not-authorized'
}).constant('USER_ROLES', {
admin: 'admin_role',
public: 'public_role'
});[ /code][code]
controllers.js
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicModal, $timeout, $state, $ionicPopup, AuthService, AUTH_EVENTS) {
$scope.username = AuthService.username();$scope.$on(AUTH_EVENTS.notAuthorized, function(event) {
var alertPopup = $ionicPopup.alert({
title: 'Unauthorized!',
template: 'You are not allowed to access this resource.'
});
});$scope.$on(AUTH_EVENTS.notAuthenticated, function(event) {
AuthService.logout();
$state.go('app.login');
});$scope.setCurrentUsername = function(name) {
$scope.username = name;
};
})
.controller('LoginCtrl', function($scope, $state, $ionicPopup, $http, AuthService) {
$scope.data = {};$scope.login = function(data) {
AuthService.login(data.username, data.password).then(function(authenticated) { $state.go('app.dashboard', {}, {reload: true}); $scope.setCurrentUsername(data.username); }, function(err) { var alertPopup = $ionicPopup.alert({ title: 'Login failed!', template: 'Please check your credentials!' }); });
};
}); [ /code][ code]
login.php
<?php
header('Content-type: application/json');$server = "localhost";
$username = "root";
$password = "teste";
$database = "teste";$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);if(isset($POST['username'],$POST['password'])){
$email=$POST['username']; $password=$POST['password'];
$query=mysql_query("SELECT * FROM users WHERE username='".$email."' AND password='".$password."'");
if(mysql_num_rows($query)>0){
$json=true;
echo json_encode($json);
}else{$json=false;
echo json_encode($json);
}
}header('Content-type: application/json'); header("Access-Control-Allow-Origin: *");
?>
[ /code]
Posts: 2
Participants: 1