<commit_before>/* Greenlight Google Maps */

var map;
var directionsDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var geocoder;
var AllArrond = [];

// Starting Position (Maybe change)
var quebec = new google.maps.LatLng(46.810811, -71.215439);
latlng = quebec;

var styles =
[
    { "stylers":
        [
            { "hue": "#00ff91" }
        ]
    },
    { "featureType": "road", "elementType": "geometry", "stylers":
        [
            { "visibility": "simplified" },
            { "hue": "#ff8800" }, { "lightness": 25 }
        ]
    },
    { "featureType": "road", "elementType": "labels", "stylers":
        [
            { "visibility": "off" }
        ]
    }
];

var styledMap = new google.maps.StyledMapType(styles,{name: "Styled Map"});
function initialize(pos)
{
        // Instantiate a directions service.
        directionsService = new google.maps.DirectionsService();
        geocoder = new google.maps.Geocoder();
        // Create a map and center it on Manhattan.

       var mapOptions = {
                zoom:11,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center:pos,
                scrollwheel: false,
                mapTypeControl:false,
                streetViewControl: false,
                panControl: true,
        }

        if(Modernizr.touch)
        {
                mapOptions.draggable = false;
        }
        map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
        // Create a renderer for directions and bind it to the map.
        var rendererOptions = {
                map: map
        }
        directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)
        // Instantiate an info window to hold step text.
        stepDisplay = new google.maps.InfoWindow();

        map.mapTypes.set('map_style', styledMap);
        map.setMapTypeId('map_style');

        TraceArrondissements();
}

var ArrondissementData = [];
function TraceArrondissements()
{
    jQuery.ajax({
          url: 'assets/qcdata/ARROND.JSON',
          type: 'GET',
          dataType: 'json',
          complete: function(xhr, textStatus) {
            //called when complete
          },
          success: function(data, textStatus, xhr) {
        $.each(data.Arrondissements.Arrondissement, function(key,value){

            ArrondissementData[key] = {};
            ArrondissementData[key].Nom = value.Nom;
            ArrondissementData[key].Abreviation = value.Abreviation;

            var polydata = value.Geometrie.split('((');
                polydata = polydata[1].split('))');
                polydata = polydata[0];
                polydata = polydata.split(',');

            for(var u = 0;u<polydata.length;u++)
            {
                polydata[u] = polydata[u].split(' ');

                polydata[u] = new google.maps.LatLng(polydata[u][1], polydata[u][0]);
            }

                    var shape = new google.maps.Polygon({
                        paths: polydata,
                        strokeColor: '#717070',
                        strokeOpacity: 0.3,
                        strokeWeight: 2,
                        fillColor: '#4B84FD',
                        fillOpacity: 0.1
                      });

                    AllArrond.push(polydata);
                    shape.setMap(map);

        });

      },
      error: function(xhr, textStatus, errorThrown) {

      }
    });
}

function CheckPoint()
{
    var test = false;
    for(var u=0;u<AllArrond.length;u++)
    {
        var polygon = new google.maps.Polygon({path:AllArrond[u]});

        if (polygon.Contains(latlng)) {
            test = true;
            break;
        }
    }

    if(!test) {
        alert('La localisation n\'est pas dans la zone couverte par la ville');
    }

    return test;
}

function GetArrondissement(object)
{
    var Gpoint;

    if(typeof object == "object")
    {
        Gpoint = new google.maps.LatLng(point.lat, point.lon);
    }
    else
    {
        geocoder.geocode( { 'address': object}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                Gpoint = new google.maps.LatLng(results[0].geometry.location.hb, results[0].geometry.location.ib);
            }
        });
    }

    for(var u=0;u<AllArrond.length;u++)
    {
        var polygon = new google.maps.Polygon({path:AllArrond[u]});

        if (polygon.Contains(Gpoint)) {
            return ArrondissementData[u];
            break;
        }
    }
}

function debugMsgNoGeoloc(){
    if(greenlight.DEBUG){
        console.log('Your device does not support geolocation');
    }
}

function PlaceCurrentLocationMarker(){
    /* Depending on available features, gets location
       directly from device, or uses google API to
       get latitude & longitude coordinates.

       Stores it in the "latlng" global as a
       google.maps.LatLng instance.
     */

    clearOverlays();

    // Is the current location event relevant ?
    // The user decides.
    if(! $('#chk-use-my-location').is(':checked') ){
        debugMsgNoGeoloc();
        return;
    }

    // Not touch screen means not mobile, in 99% cases
    if(!Modernizr.touch){
        debugMsgNoGeoloc();
        return;
    }

    // No geolocation available
    if(!Modernizr.geolocation){
        debugMsgNoGeoloc();
        return;
    }

    if(!navigator.geolocation)
    {
        debugMsgNoGeoloc();
        return;
    }

    navigator.geolocation.getCurrentPosition(function(position) {
        latlng = new google.maps.LatLng(
            position.coords.latitude, position.coords.longitude
        );
        setMarker(latlng);
    });

}

function setMarker(latlng){
    /*
     * This function places a marker on the map
     * with a funny bouncy animation.
     * latlng must be a google.maps.LatLng instance
     * */

    $('#AddressError').fadeOut();
    map.setCenter(latlng);

    var image = 'assets/img/map-pointer.png';

    var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        icon: image,
    });

    marker.setAnimation(google.maps.Animation.BOUNCE);

    $(marker).delay(2000).queue(function( nxt ) {
        marker.setAnimation(null);
    });

    markerArray.push(marker);

}

function PlaceAddressMarker(address) {

    clearOverlays();

    if(!address)
        address = $('#address_string').val();

    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var loc = results[0].geometry.location;
            latlng = new google.maps.LatLng( loc.lat(), loc.lng() );
            setMarker(latlng);
        } else {
            $('#AddressError').fadeIn();
            if(greenlight.DEBUG){
                console.log('Google Maps API could not geolocate this address');
            }
        }
    });
}

function clearOverlays() {
    if (markerArray) {
        for (i in markerArray) {
            markerArray[i].setMap(null);
        }
    }
}

function ResizeMap() {
    initialize(latlng);
    var marker = new google.maps.Marker({
        map: map,
        position: latlng
    });
}

$(document).ready(function() {

    /*********** Google Map autocomplete */
    var input = document.getElementById('address_string');
    var autocomplete = new google.maps.places.Autocomplete(input);

    var infowindow = new google.maps.InfoWindow();

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        infowindow.close();
        input.className = '';
        var place = autocomplete.getPlace();
        if (!place.geometry) {
            // Inform the user that the place was not found and return.
            input.className = 'notfound';
            return;
        }
        // If the place has a geometry, then present it on a map.
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(13); // Why 13? Because it looks good.
        }
        var image = {
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(35, 35)
        };
        var address = '';
        PlaceAddressMarker();
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
            ].join(' ');
        }
        infowindow.setContent('
' + place.name + '
' + address);
    });

    /*********** Google Map autocomplete */

    google.maps.Polygon.prototype.Contains = function(point) {
        // ray casting alogrithm http://rosettacode.org/wiki/Ray-casting_algorithm
        var crossings = 0,
            path = this.getPath();

        // for each edge
        for (var i=0; i < path.getLength(); i++) {
            var a = path.getAt(i),
                j = i + 1;
            if (j >= path.getLength()) {
                j = 0;
            }
            var b = path.getAt(j);
            if (rayCrossesSegment(point, a, b)) {
                crossings++;
            }
        }

        // odd number of crossings?
        return (crossings % 2 == 1);

        function rayCrossesSegment(point, a, b) {
            var px = point.lng(),
                py = point.lat(),
                ax = a.lng(),
                ay = a.lat(),
                bx = b.lng(),
                by = b.lat();
            if (ay > by) {
                ax = b.lng();
                ay = b.lat();
                bx = a.lng();
                by = a.lat();
            }
            // alter longitude to cater for 180 degree crossings
            if (px < 0) { px += 360 };
            if (ax < 0) { ax += 360 };
            if (bx < 0) { bx += 360 };

            if (py == ay || py == by) py += 0.00000001;
            if ((py > by || py < ay) || (px > Math.max(ax, bx))) return false;
            if (px < Math.min(ax, bx)) return true;

            var red = (ax != bx) ? ((by - ay) / (bx - ax)) : Infinity;
            var blue = (ax != px) ? ((py - ay) / (px - ax)) : Infinity;
            return (blue >= red);

        }

     };

    $('#address_string').on('input', function() {
        PlaceAddressMarker();
    });

    $('#address_string').bind('keypress', function(e) {
        if(e.keyCode==13){
           PlaceAddressMarker();
        }
        // Enter pressed... do anything here...
    });

    initialize(quebec);
    PlaceCurrentLocationMarker();
    window.addEventListener('resize', ResizeMap, false);

});
<commit_msg>Fix Bug marker<commit_after>/* Greenlight Google Maps */

var map;
var directionsDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var geocoder;
var AllArrond = [];

// Starting Position (Maybe change)
var quebec = new google.maps.LatLng(46.810811, -71.215439);
latlng = quebec;

var styles =
[
    { "stylers":
        [
            { "hue": "#00ff91" }
        ]
    },
    { "featureType": "road", "elementType": "geometry", "stylers":
        [
            { "visibility": "simplified" },
            { "hue": "#ff8800" }, { "lightness": 25 }
        ]
    },
    { "featureType": "road", "elementType": "labels", "stylers":
        [
            { "visibility": "off" }
        ]
    }
];

var styledMap = new google.maps.StyledMapType(styles,{name: "Styled Map"});
function initialize(pos)
{
        // Instantiate a directions service.
        directionsService = new google.maps.DirectionsService();
        geocoder = new google.maps.Geocoder();
        // Create a map and center it on Manhattan.

       var mapOptions = {
                zoom:11,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center:pos,
                scrollwheel: false,
                mapTypeControl:false,
                streetViewControl: false,
                panControl: true,
        }

        if(Modernizr.touch)
        {
                mapOptions.draggable = false;
        }
        map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
        // Create a renderer for directions and bind it to the map.
        var rendererOptions = {
                map: map
        }
        directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)
        // Instantiate an info window to hold step text.
        stepDisplay = new google.maps.InfoWindow();

        map.mapTypes.set('map_style', styledMap);
        map.setMapTypeId('map_style');

        TraceArrondissements();
}

var ArrondissementData = [];
function TraceArrondissements()
{
    jQuery.ajax({
          url: 'assets/qcdata/ARROND.JSON',
          type: 'GET',
          dataType: 'json',
          complete: function(xhr, textStatus) {
            //called when complete
          },
          success: function(data, textStatus, xhr) {
        $.each(data.Arrondissements.Arrondissement, function(key,value){

            ArrondissementData[key] = {};
            ArrondissementData[key].Nom = value.Nom;
            ArrondissementData[key].Abreviation = value.Abreviation;

            var polydata = value.Geometrie.split('((');
                polydata = polydata[1].split('))');
                polydata = polydata[0];
                polydata = polydata.split(',');

            for(var u = 0;u<polydata.length;u++)
            {
                polydata[u] = polydata[u].split(' ');

                polydata[u] = new google.maps.LatLng(polydata[u][1], polydata[u][0]);
            }

                    var shape = new google.maps.Polygon({
                        paths: polydata,
                        strokeColor: '#717070',
                        strokeOpacity: 0.3,
                        strokeWeight: 2,
                        fillColor: '#4B84FD',
                        fillOpacity: 0.1
                      });

                    AllArrond.push(polydata);
                    shape.setMap(map);

        });

      },
      error: function(xhr, textStatus, errorThrown) {

      }
    });
}

function CheckPoint()
{
    var test = false;
    for(var u=0;u<AllArrond.length;u++)
    {
        var polygon = new google.maps.Polygon({path:AllArrond[u]});

        if (polygon.Contains(latlng)) {
            test = true;
            break;
        }
    }

    if(!test) {
        alert('La localisation n\'est pas dans la zone couverte par la ville');
    }

    return test;
}

function GetArrondissement(object)
{
    var Gpoint;

    if(typeof object == "object")
    {
        Gpoint = new google.maps.LatLng(point.lat, point.lon);
    }
    else
    {
        geocoder.geocode( { 'address': object}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                Gpoint = new google.maps.LatLng(results[0].geometry.location.hb, results[0].geometry.location.ib);
            }
        });
    }

    for(var u=0;u<AllArrond.length;u++)
    {
        var polygon = new google.maps.Polygon({path:AllArrond[u]});

        if (polygon.Contains(Gpoint)) {
            return ArrondissementData[u];
            break;
        }
    }
}

function debugMsgNoGeoloc(){
    if(greenlight.DEBUG){
        console.log('Your device does not support geolocation');
    }
}

function PlaceCurrentLocationMarker(){
    /* Depending on available features, gets location
       directly from device, or uses google API to
       get latitude & longitude coordinates.

       Stores it in the "latlng" global as a
       google.maps.LatLng instance.
     */

    clearOverlays();

    // Is the current location event relevant ?
    // The user decides.
    if(! $('#chk-use-my-location').is(':checked') ){
        debugMsgNoGeoloc();
        return;
    }

    // Not touch screen means not mobile, in 99% cases
    if(!Modernizr.touch){
        debugMsgNoGeoloc();
        return;
    }

    // No geolocation available
    if(!Modernizr.geolocation){
        debugMsgNoGeoloc();
        return;
    }

    if(!navigator.geolocation)
    {
        debugMsgNoGeoloc();
        return;
    }

    navigator.geolocation.getCurrentPosition(function(position) {
        latlng = new google.maps.LatLng(
            position.coords.latitude, position.coords.longitude
        );
        setMarker(latlng);
    });

}

function setMarker(latlng){
    /*
     * This function places a marker on the map
     * with a funny bouncy animation.
     * latlng must be a google.maps.LatLng instance
     * */

    $('#AddressError').fadeOut();
    map.setCenter(latlng);

    var image = 'assets/img/map-pointer.png';

    var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        icon: image,
    });

    marker.setAnimation(google.maps.Animation.BOUNCE);

    $(marker).delay(2000).queue(function( nxt ) {
        marker.setAnimation(null);
    });

    markerArray.push(marker);

}

function PlaceAddressMarker(address) {

    clearOverlays();

    if(!address)
        address = $('#address_string').val();

    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var loc = results[0].geometry.location;
            latlng = new google.maps.LatLng( loc.lat(), loc.lng() );
            setMarker(latlng);
        } else {
            $('#AddressError').fadeIn();
            if(greenlight.DEBUG){
                console.log('Google Maps API could not geolocate this address');
            }
        }
    });
}

function clearOverlays() {
    if (markerArray) {
        for (i in markerArray) {
            markerArray[i].setMap(null);
        }
    }
}

function ResizeMap() {
    initialize(latlng);
    setMarker(latlng);
}

$(document).ready(function() {

    /*********** Google Map autocomplete */
    var input = document.getElementById('address_string');
    var autocomplete = new google.maps.places.Autocomplete(input);

    var infowindow = new google.maps.InfoWindow();

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        infowindow.close();
        input.className = '';
        var place = autocomplete.getPlace();
        if (!place.geometry) {
            // Inform the user that the place was not found and return.
            input.className = 'notfound';
            return;
        }
        // If the place has a geometry, then present it on a map.
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(13); // Why 13? Because it looks good.
        }
        var image = {
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(35, 35)
        };
        var address = '';
        PlaceAddressMarker();
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
            ].join(' ');
        }
        infowindow.setContent('
' + place.name + '
' + address);
    });

    /*********** Google Map autocomplete */

    google.maps.Polygon.prototype.Contains = function(point) {
        // ray casting alogrithm http://rosettacode.org/wiki/Ray-casting_algorithm
        var crossings = 0,
            path = this.getPath();

        // for each edge
        for (var i=0; i < path.getLength(); i++) {
            var a = path.getAt(i),
                j = i + 1;
            if (j >= path.getLength()) {
                j = 0;
            }
            var b = path.getAt(j);
            if (rayCrossesSegment(point, a, b)) {
                crossings++;
            }
        }

        // odd number of crossings?
        return (crossings % 2 == 1);

        function rayCrossesSegment(point, a, b) {
            var px = point.lng(),
                py = point.lat(),
                ax = a.lng(),
                ay = a.lat(),
                bx = b.lng(),
                by = b.lat();
            if (ay > by) {
                ax = b.lng();
                ay = b.lat();
                bx = a.lng();
                by = a.lat();
            }
            // alter longitude to cater for 180 degree crossings
            if (px < 0) { px += 360 };
            if (ax < 0) { ax += 360 };
            if (bx < 0) { bx += 360 };

            if (py == ay || py == by) py += 0.00000001;
            if ((py > by || py < ay) || (px > Math.max(ax, bx))) return false;
            if (px < Math.min(ax, bx)) return true;

            var red = (ax != bx) ? ((by - ay) / (bx - ax)) : Infinity;
            var blue = (ax != px) ? ((py - ay) / (px - ax)) : Infinity;
            return (blue >= red);

        }

     };

    $('#address_string').on('input', function() {
        PlaceAddressMarker();
    });

    $('#address_string').bind('keypress', function(e) {
        if(e.keyCode==13){
           PlaceAddressMarker();
        }
        // Enter pressed... do anything here...
    });

    initialize(quebec);
    PlaceCurrentLocationMarker();
    window.addEventListener('resize', ResizeMap, false);

});
<|endoftext|>


<commit_before>$(document).ready(getposts);
function getposts(){

    $.getJSON('entries.json', function(data) {
		$.each(data.entries.reverse(), function(key, val) {
                var output="
";
				    output+="
" + val.date +"
";
				    output+="
" + val.title +"
";
				    output+="
" + val.text +"
";
				    output+="
";
					output+="
";

				$("#blog").append(output);
				$('#blog').paginate({itemsPerPage: 2});
      	});
    });
}

$('#search2').keyup(function () {
    var searchField = $('#search2').val();
    if (searchField.length)
    {
    var myExp = new RegExp(searchField, "i");
    var found = 0;

   $.getJSON('entries.json', function (data) {
   var output = '
';

   $.each(data.entries, function(key, val) {
      if (val.title.search(myExp) !== -1) {
      console.log(val);
      found = 1;
      output += '
';
      output += '
';
      output += '
' + val.date + '
';
      output += '
' + val.title + '
';
      output += '
' + val.text + '
';
      output += '
';
      }
   });
      output += '
';
      if (found==1) {
      $('#update').removeClass('update-hidden');
      $('#update').html(output);
      }
      else {
          $('#update').addClass('update-hidden');
      }

});
    } else {
      $('#update').addClass('update-hidden');
    }
});
<commit_msg>Styling changes<commit_after>$(document).ready(getposts);
function getposts(){

    $.getJSON('entries.json', function(data) {
		$.each(data.entries.reverse(), function(key, val) {
                var output="
";
				    output+="
" + val.date +"
";
				    output+="
" + val.title +"
";
				    output+="
" + val.text +"
";
				    output+="
";
					output+="
";

				$("#blog").append(output);
				$('#blog').paginate({itemsPerPage: 2});
      	});
    });
}

$('#search2').keyup(function () {
    var searchField = $('#search2').val();
    if (searchField.length)
    {
    var myExp = new RegExp(searchField, "i");
    var found = 0;

   $.getJSON('entries.json', function (data) {
   var output = '
';

   $.each(data.entries, function(key, val) {
      if (val.title.search(myExp) !== -1) {
      console.log(val);
      found = 1;
      output += '
';
      output += '
';
      output += '
' + val.date + '
';
      output += '
' + val.title + '
';
      output += '
' + val.text + '
';
      output += '
';
      }
   });
      output += '
';
      if (found==1) {
      $('#update').removeClass('update-hidden');
      $('#update').html(output);
      }
      else {
          $('#update').addClass('update-hidden');
      }

});
    } else {
      $('#update').addClass('update-hidden');
    }
});
<|endoftext|>


<commit_before>var toneControl = (function () {

	destroy = function (scheduler) {
		window.clearInterval(scheduler);
	};

	create = function(freq, lvl, intv, dur) {
		var fire_intv = intv + dur;
		new Tone.Oscillator({
			"type": "square",
			"frequency" : freq,
			"volume" : lvl
		}).toMaster().start();
		window.setTimeout(function() {
			Tone.Master.mute = true;
		}, dur);
		return window.setInterval(function() {
			window.setTimeout(function() {
				Tone.Master.mute = true;
			}, fire_intv);
			window.setTimeout(function() {
				Tone.Master.mute = false;
			}, intv);
		}, fire_intv);
	};

	return {
		create: create,
		destroy: destroy
	};

})();
<commit_msg>stop tones, so freq won't stack.<commit_after>var tones = [];
var toneControl = (function () {

	destroy = function (tid) {
		window.clearInterval(tid);
		tones[tid].stop();
	};

	create = function(freq, lvl, intv, dur) {
		var fire_intv = intv + dur;
		var tone = new Tone.Oscillator({
			"type": "square",
			"frequency" : freq,
			"volume" : lvl
		}).toMaster().start();
		window.setTimeout(function() {
			Tone.Master.mute = true;
		}, dur);
		var tid = window.setInterval(function() {
			window.setTimeout(function() {
				Tone.Master.mute = true;
			}, fire_intv);
			window.setTimeout(function() {
				Tone.Master.mute = false;
			}, intv);
		}, fire_intv);
		tones[tid] = tone;
		return tid;
	};

	return {
		create: create,
		destroy: destroy
	};

})();
<|endoftext|>


<commit_before>function TempoEvent(type, item, element) {
    this.type = type;
    this.item = item;
    this.element = element;

    return this;
}

TempoEvent.Types = {
    RENDER_STARTING : 'render_starting',
    ITEM_RENDER_STARTING : 'item_render_starting',
    ITEM_RENDER_COMPLETE : 'item_render_complete',
    RENDER_COMPLETE : 'render_complete'
};

var Tempo = (function (tempo) {

    /*!
     * Helpers
     */
    var utils = {
        startsWith : function (str, prefix) {
            return (str.indexOf(prefix) === 0);
        },

        replaceVariable : function (item, str) {
            return str.replace(/\{\{([A-Za-z0-9\._\[\]]*?)\}\}/g, function (match, variable) {
				var val = null;
				if (utils.typeOf(item) === 'array') {
					val = eval('item' + variable);
				} else {
					val = eval('item.' + variable);
				}
                if (val !== undefined) {
                    return val;
                }
                return '';
            });
        },

        clearContainer : function (el) {
            if (el !== undefined && el.childNodes !== undefined) {
                for (var i = el.childNodes.length; i >= 0; i--) {
                    if (el.childNodes[i] !== undefined && el.childNodes[i].getAttribute !== undefined && el.childNodes[i].getAttribute('data-template') !== null) {
                        el.childNodes[i].parentNode.removeChild(el.childNodes[i]);
                    }
                }
            }
        },

        isNested : function (el) {
            var p = el.parentNode;
            while (p) {
                if (p.getAttribute !== undefined && p.getAttribute('data-template') !== null) {
                    return true;
                }
                p = p.parentNode;
            }
            return false;
        },

        equalsIgnoreCase : function (str1, str2) {
            return str1.toLowerCase() === str2.toLowerCase();
        },

        getElement : function (template, html) {
            if (utils.equalsIgnoreCase(template.tagName, 'tr')) {
                // Wrapping to get around read-only innerHTML
                var el = document.createElement('div');
                el.innerHTML = '

' + html + '

';
                var depth = 3;
                while (depth--) {
                    el = el.lastChild;
                }
                return el;
            } else {
                // No need to wrap
                template.innerHTML = html;
                return template;
            }
        },

        typeOf : function (obj) {
            if (typeof(obj) === "object") {
                if (obj === null) {
                    return "null";
                }
                if (obj.constructor === ([]).constructor) {
                    return "array";
                }
                if (obj.constructor === (new Date()).constructor) {
                    return "date";
                }
                if (obj.constructor === (new RegExp()).constructor) {
                    return "regex";
                }
                return "object";
            }
            return typeof(obj);
        },

        notify : function (listener, event) {
            if (listener !== undefined) {
                listener(event);
            }
        }
    };

    function Templates(nestedItem) {
        this.defaultTemplate = null;
        this.namedTemplates = {};
        this.container = null;
		this.nestedItem = nestedItem !== undefined ? nestedItem : null;

        return this;
    }

    Templates.prototype = {
        parse: function (container) {
            this.container = container;
            var children = container.getElementsByTagName('*');

            for (var i = 0; i < children.length; i++) {
                if (children[i].getAttribute !== undefined && children[i].getAttribute('data-template') !== null && (this.nestedItem === children[i].getAttribute('data-template') || children[i].getAttribute('data-template') === '' && !utils.isNested(children[i]))) {
                    this.createTemplate(children[i]);
                }
            }

			// If there is no default template (data-template) then create one from container
			if (this.defaultTemplate === null) {
				// Creating a template inside the container
				var el = document.createElement('div');
				el.setAttribute('data-template', '');
				el.innerHTML = this.container.innerHTML;

				// Clearing container before adding the wrapped contents
				this.container.innerHTML = '';

				// There is now a default template present with a data-template attribute
				this.container.appendChild(el);
				this.createTemplate(el);
			}

            utils.clearContainer(this.container);
        },

        createTemplate : function (node) {
            var element = node.cloneNode(true);

            // Clear display: none;
            if (element.style.removeAttribute) {
                element.style.removeAttribute("display");
            }
            else {
                element.style.removeProperty("display");
            }

            // Remapping container element in case template
            // is deep in container
			this.container = node.parentNode;

            // Element is a template
			var nonDefault = false;
            for (var a = 0; a < element.attributes.length; a++) {
                var attr = element.attributes[a];
                // If attribute
                if (utils.startsWith(attr.name, 'data-if-')) {
                    var val;
                    if (attr.value === '') {
                        val = true;
                    } else {
                        val = '\'' + attr.value + '\'';
                    }
                    this.namedTemplates[attr.name.substring(8, attr.name.length) + '==' + val] = element;
                    element.removeAttribute(attr.name);
					nonDefault = true;
                }
            }

            // Setting as default template, last one wins
            if (!nonDefault) {
				this.defaultTemplate = element;
			}
        },

        templateFor: function (item) {
            for (var templateName in this.namedTemplates) {
                if (eval('item.' + templateName)) {
                    return this.namedTemplates[templateName].cloneNode(true);
                }
            }
            if (this.defaultTemplate) {
                return this.defaultTemplate.cloneNode(true);
            }
        }
    };

    /*!
     * Renderer for populating containers with data using templates.
     */
    function Renderer(templates) {
        this.templates = templates;
        this.listener = undefined;
        this.started = false;

        return this;
    }

    Renderer.prototype = {
        notify : function (listener) {
            this.listener = listener;

            return this;
        },

        starting : function () {
            // Use this to manually fire the RENDER_STARTING event e.g. just before you issue an AJAX request
            // Useful if you're not calling prepare immediately before render
            this.started = true;
            utils.notify(this.listener, new TempoEvent(TempoEvent.Types.RENDER_STARTING, undefined, undefined));

            return this;
        },

        render : function (data) {
            // Check if starting event was manually fired
            if (!this.started) {
                utils.notify(this.listener, new TempoEvent(TempoEvent.Types.RENDER_STARTING, undefined, undefined));
            }

            utils.clearContainer(this.templates.container);

            if (data) {
                // If object then wrapping in an array
                if (utils.typeOf(data) === 'object') {
                    data = [data];
                }

                var fragment = document.createDocumentFragment();

                for (var i = 0; i < data.length; i++) {
                    this.renderItem(this, data[i], fragment);
                }

                this.templates.container.appendChild(fragment);
            }

            utils.notify(this.listener, new TempoEvent(TempoEvent.Types.RENDER_COMPLETE, undefined, undefined));

            return this;
        },

        renderItem : function (renderer, item, fragment) {
            var template = renderer.templates.templateFor(item);
            if (template && item) {
                utils.notify(this.listener, new TempoEvent(TempoEvent.Types.ITEM_RENDER_STARTING, item, template));

                var nestedDeclaration = template.innerHTML.match(/data-template="(.*?)"/g);
				if (nestedDeclaration) {
					for (var i = 0; i < nestedDeclaration.length; i++) {
						var nested = nestedDeclaration[i].match(/"(.*?)"/)[1];

						var t = new Templates(nested);
	                    t.parse(template);

	                    var r = new Renderer(t);
	                    r.render(eval('item.' + nested));
					}
				}

                // Dealing with HTML as a String from now on (to be reviewed)
				// Attribute values are escaped in FireFox so making sure there are no escaped tags
                var html = template.innerHTML.replace(/%7B%7B/g, '{{').replace(/%7D%7D/g, '}}');

                // Tags
                for (var p in renderer.tags) {
                    html = html.replace(new RegExp(renderer.tags[p].regex, 'gi'), renderer.tags[p].handler(renderer, item));
                }

                // Content
                html = utils.replaceVariable(item, html);

                // Template class attribute
                if (template.getAttribute('class')) {
                    template.className = utils.replaceVariable(item, template.className);
                }

                // Template id
                if (template.getAttribute('id')) {
                    template.id = utils.replaceVariable(item, template.id);
                }

                fragment.appendChild(utils.getElement(template, html));

                utils.notify(this.listener, new TempoEvent(TempoEvent.Types.ITEM_RENDER_COMPLETE, item, template));
            }
        },

        tags : [
            // If tag
            {'regex': '\\{\\{if ([\\s\\S]*?)\\}\\}([\\s\\S]*?)\\{\\{endif\\}\\}', 'handler': function (renderer, item) {
                return function (match, condition, content) {
                    var member_regex = '';
                    for (var member in item) {
                        if (member_regex.length > 0) {
                            member_regex += '|';
                        }
                        member_regex += member;
                    }

                    condition = condition.replace(/&/g, '&');
                    condition = condition.replace(new RegExp(member_regex, 'gi'), function (match) {
                        return 'item.' + match;
                    });

                    if (eval(condition)) {
                        return content;
                    }

                    return '';
                };
            }
            }
        ]
    };

    /*!
     * Prepare a container for rendering, gathering templates and
     * clearing afterwards.
     */
    tempo.prepare = function (container) {
        if (typeof container === 'string') {
            container = document.getElementById(container);
        }

        var templates = new Templates();
        templates.parse(container);

        return new Renderer(templates);
    };

    return tempo;

})(Tempo || {});
<commit_msg>yay working, bit of doc<commit_after>function TempoEvent(type, item, element) {
    this.type = type;
    this.item = item;
    this.element = element;

    return this;
}

TempoEvent.Types = {
    RENDER_STARTING : 'render_starting',
    ITEM_RENDER_STARTING : 'item_render_starting',
    ITEM_RENDER_COMPLETE : 'item_render_complete',
    RENDER_COMPLETE : 'render_complete'
};

var Tempo = (function (tempo) {

    /*!
     * Helpers
     */
    var utils = {
        startsWith : function (str, prefix) {
            return (str.indexOf(prefix) === 0);
        },

        replaceVariable : function (item, str) {
            return str.replace(/\{\{([A-Za-z0-9\._\[\]]*?)\}\}/g, function (match, variable) {
				var val = null;
				if (utils.typeOf(item) === 'array') {
					val = eval('item' + variable);
				} else {
					val = eval('item.' + variable);
				}
                if (val !== undefined) {
                    return val;
                }
                return '';
            });
        },

        clearContainer : function (el) {
            if (el !== undefined && el.childNodes !== undefined) {
                for (var i = el.childNodes.length; i >= 0; i--) {
                    if (el.childNodes[i] !== undefined && el.childNodes[i].getAttribute !== undefined && el.childNodes[i].getAttribute('data-template') !== null) {
                        el.childNodes[i].parentNode.removeChild(el.childNodes[i]);
                    }
                }
            }
        },

        isNested : function (el) {
            var p = el.parentNode;
            while (p) {
                if (p.getAttribute !== undefined && p.getAttribute('data-template') !== null) {
                    return true;
                }
                p = p.parentNode;
            }
            return false;
        },

        equalsIgnoreCase : function (str1, str2) {
            return str1.toLowerCase() === str2.toLowerCase();
        },

        getElement : function (template, html) {
            if (utils.equalsIgnoreCase(template.tagName, 'tr')) {
                // Wrapping to get around read-only innerHTML
                var el = document.createElement('div');
                el.innerHTML = '

' + html + '

';
                var depth = 3;
                while (depth--) {
                    el = el.lastChild;
                }
                return el;
            } else {
                // No need to wrap
                template.innerHTML = html;
                return template;
            }
        },

        typeOf : function (obj) {
            if (typeof(obj) === "object") {
                if (obj === null) {
                    return "null";
                }
                if (obj.constructor === ([]).constructor) {
                    return "array";
                }
                if (obj.constructor === (new Date()).constructor) {
                    return "date";
                }
                if (obj.constructor === (new RegExp()).constructor) {
                    return "regex";
                }
                return "object";
            }
            return typeof(obj);
        },

        notify : function (listener, event) {
            if (listener !== undefined) {
                listener(event);
            }
        }
    };

    function Templates(nestedItem) {
        this.defaultTemplate = null;
        this.namedTemplates = {};
        this.container = null;
		this.nestedItem = nestedItem !== undefined ? nestedItem : null;

        return this;
    }

    Templates.prototype = {
        parse: function (container) {
            this.container = container;
            var children = container.getElementsByTagName('*');

            for (var i = 0; i < children.length; i++) {
                if (children[i].getAttribute !== undefined && children[i].getAttribute('data-template') !== null && (this.nestedItem === children[i].getAttribute('data-template') || children[i].getAttribute('data-template') === '' && !utils.isNested(children[i]))) {
                    this.createTemplate(children[i]);
                }
            }

			// If there is no default template (data-template) then create one from container
			if (this.defaultTemplate === null) {
				// Creating a template inside the container
				var el = document.createElement('div');
				el.setAttribute('data-template', '');
				el.innerHTML = this.container.innerHTML;

				// Clearing container before adding the wrapped contents
				this.container.innerHTML = '';

				// There is now a default template present with a data-template attribute
				this.container.appendChild(el);
				this.createTemplate(el);
			}

            utils.clearContainer(this.container);
        },

        createTemplate : function (node) {
            var element = node.cloneNode(true);

            // Clear display: none;
            if (element.style.removeAttribute) {
                element.style.removeAttribute("display");
            }
            else {
                element.style.removeProperty("display");
            }

            // Remapping container element in case template
            // is deep in container
			this.container = node.parentNode;

            // Element is a template
			var nonDefault = false;
            for (var a = 0; a < element.attributes.length; a++) {
                var attr = element.attributes[a];
                // If attribute
                if (utils.startsWith(attr.name, 'data-if-')) {
                    var val;
                    if (attr.value === '') {
                        val = true;
                    } else {
                        val = '\'' + attr.value + '\'';
                    }
                    this.namedTemplates[attr.name.substring(8, attr.name.length) + '==' + val] = element;
                    element.removeAttribute(attr.name);
					nonDefault = true;
                }
            }

            // Setting as default template, last one wins
            if (!nonDefault) {
				this.defaultTemplate = element;
			}
        },

        templateFor: function (item) {
            for (var templateName in this.namedTemplates) {
                if (eval('item.' + templateName)) {
                    return this.namedTemplates[templateName].cloneNode(true);
                }
            }
            if (this.defaultTemplate) {
                return this.defaultTemplate.cloneNode(true);
            }
        }
    };

    /*!
     * Renderer for populating containers with data using templates.
     */
    function Renderer(templates) {
        this.templates = templates;
        this.listener = undefined;
        this.started = false;

        return this;
    }

    Renderer.prototype = {
        notify : function (listener) {
            this.listener = listener;

            return this;
        },

        starting : function () {
            // Use this to manually fire the RENDER_STARTING event e.g. just before you issue an AJAX request
            // Useful if you're not calling prepare immediately before render
            this.started = true;
            utils.notify(this.listener, new TempoEvent(TempoEvent.Types.RENDER_STARTING, undefined, undefined));

            return this;
        },

        render : function (data) {
            // Check if starting event was manually fired
            if (!this.started) {
                utils.notify(this.listener, new TempoEvent(TempoEvent.Types.RENDER_STARTING, undefined, undefined));
            }

            utils.clearContainer(this.templates.container);

            if (data) {
                // If object then wrapping in an array
                if (utils.typeOf(data) === 'object') {
                    data = [data];
                }

                var fragment = document.createDocumentFragment();

                for (var i = 0; i < data.length; i++) {
                    this.renderItem(this, data[i], fragment);
                }

                this.templates.container.appendChild(fragment);
            }

            utils.notify(this.listener, new TempoEvent(TempoEvent.Types.RENDER_COMPLETE, undefined, undefined));

            return this;
        },

        renderItem : function (renderer, item, fragment) {
            var template = renderer.templates.templateFor(item);
            if (template && item) {
                utils.notify(this.listener, new TempoEvent(TempoEvent.Types.ITEM_RENDER_STARTING, item, template));

                var nestedDeclaration = template.innerHTML.match(/data-template="(.*?)"/g);
				if (nestedDeclaration) {
					for (var i = 0; i < nestedDeclaration.length; i++) {
						var nested = nestedDeclaration[i].match(/"(.*?)"/)[1];

						var t = new Templates(nested);
	                    t.parse(template);

	                    var r = new Renderer(t);
	                    r.render(eval('item.' + nested));
					}
				}

                // Dealing with HTML as a String from now on (to be reviewed)
				// Attribute values are escaped in FireFox so making sure there are no escaped tags
                var html = template.innerHTML.replace(/%7B%7B/g, '{{').replace(/%7D%7D/g, '}}');

                // Tags
                for (var p in renderer.tags) {
                    html = html.replace(new RegExp(renderer.tags[p].regex, 'gi'), renderer.tags[p].handler(renderer, item));
                }

                // Content
                html = utils.replaceVariable(item, html);

                // Template class attribute
                if (template.getAttribute('class')) {
                    template.className = utils.replaceVariable(item, template.className);
                }

                // Template id
                if (template.getAttribute('id')) {
                    template.id = utils.replaceVariable(item, template.id);
                }

                fragment.appendChild(utils.getElement(template, html));

                utils.notify(this.listener, new TempoEvent(TempoEvent.Types.ITEM_RENDER_COMPLETE, item, template));
            }
        },

        tags : [
            // If tag (using a workaround for the dotall modifier to match multilines [\\s\\S])
            {'regex': '\\{\\{if ([\\s\\S]*?)\\}\\}([\\s\\S]*?)\\{\\{endif\\}\\}', 'handler': function (renderer, item) {
                return function (match, condition, content) {
                    var member_regex = '';
                    for (var member in item) {
                        if (member_regex.length > 0) {
                            member_regex += '|';
                        }
                        member_regex += member;
                    }

                    condition = condition.replace(/&/g, '&');
                    condition = condition.replace(new RegExp(member_regex, 'gi'), function (match) {
                        return 'item.' + match;
                    });

                    if (eval(condition)) {
                        return content;
                    }

                    return '';
                };
            }
            }
        ]
    };

    /*!
     * Prepare a container for rendering, gathering templates and
     * clearing afterwards.
     */
    tempo.prepare = function (container) {
        if (typeof container === 'string') {
            container = document.getElementById(container);
        }

        var templates = new Templates();
        templates.parse(container);

        return new Renderer(templates);
    };

    return tempo;

})(Tempo || {});
<|endoftext|>


<commit_before><commit_msg>Add sign in loging to login file<commit_after>'use strict';

var LocalStrategy = require('passport-local').Strategy,
	FacebookStrategy = require('passport-facebook').Strategy,
	User = require('../models/user');

module.exports = function(passport){
    /* - Passport session setup - */
	/* - Required for persistent login sessions & passport needs ability to serialize and unserialize users out of session. - */

    // This is used to serialize the user for the session.
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // This is used to deserialize the user.
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

	/*-----------------------------------------------Begining of local sign-in strategy.------------------------------------------------*/
	passport.use('local-sign-in', new LocalStrategy({

		usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true

		},function(req, email, password, done){
		User.findOne({'email': email /*|| username: email || phone_number: email*/}, function(err, user){
				//If any errors, return the error prior to anything else.
				if(err){
					return done(err);
				}

				//If no user is found, return login failed message.
				if(!user){
					return done(null, false, req.flash('loginMessage','No user found.'));
				}

				//If user is found, but incorrect password. return login faile message.
				if(!user.isValidPassword(password)){
					return done(null, false, req.flash('loginMessage','Opps! Wrong password.'))
				}

				//If all is well, return succesful user.
				return done(null, user);
			});
		}
	));
	/*-----------------------------------------------End of local sign-in strategy.------------------------------------------------*/

};
<|endoftext|>


<commit_before>'use strict';

var core = require('../../modules/soajs.core');
var provision = require("../../modules/soajs.provision");
var MultiTenantSession = require("../../classes/MultiTenantSession");
var async = require("async");
var Netmask = require('netmask').Netmask;
var useragent = require('useragent');
var merge = require('merge');

/**
 *
 * @param configuration
 * @returns {Function}
 */
module.exports = function (configuration) {
    var soajs = configuration.soajs;
    var param = configuration.param;
    var app = configuration.app;

    /**
     *
     * @param obj
     * @param cb
     * @returns {*}
     */
    function serviceCheck(obj, cb) {
        var system = _system.getAcl(obj);
        if (system)
            return cb(null, obj);
        else
            return cb(154);
    }

    /**
     *
     * @param obj
     * @param cb
     * @returns {*}
     */
    function securityGeoCheck(obj, cb) {
        var clientIp = obj.req.getClientIP();
        var geoAccess = obj.keyObj.geo; //{"allow": ["127.0.0.1"], "deny": []};
        obj.geo = {"ip": clientIp};

        var checkAccess = function (geoAccessArr, ip) {
            var check = geoAccessArr.some(function (addr) {
                try {
                    var block = new Netmask(addr);
                    return block.contains(ip);
                } catch (err) {
                    obj.req.soajs.log.error('Geographic security configuration failed: ', addr);
                    obj.req.soajs.log.error(err);
                }
                return false;
            });
            return check;
        };

        if (clientIp && geoAccess && geoAccess.deny && Array.isArray(geoAccess.deny)) {
            var denied = checkAccess(geoAccess.deny, clientIp);
            if (denied)
                return cb(155);
        }

        if (clientIp && geoAccess && geoAccess.allow && Array.isArray(geoAccess.allow)) {
            var allowed = checkAccess(geoAccess.allow, clientIp);
            if (!allowed)
                return cb(155);
        }

        return cb(null, obj);
    }

    /**
     *
     * @param obj
     * @param cb
     * @returns {*}
     */
    function securityDeviceCheck(obj, cb) {
        var clientUA = obj.req.getClientUserAgent();
        var deviceAccess = obj.keyObj.device; //{"allow": [{"family": "chrome"}], "deny": []};
        obj.device = clientUA;

        var validateField = function (fieldName, uaObj, da) {
            if (da[fieldName] && da[fieldName] !== '*' && uaObj[fieldName]) {
                if (typeof (da[fieldName]) === 'string') {
                    if (da[fieldName].trim().toUpperCase() !== uaObj[fieldName].trim().toUpperCase()) {
                        return false;
                    }
                    if (da[fieldName].min) {
                        if (da[fieldName].min.trim() > uaObj[fieldName].trim()) {
                            return false;
                        }
                    }
                }
                if (da[fieldName].max) {
                    if (da[fieldName].max.trim() < uaObj[fieldName].trim()) {
                        return false;
                    }
                }
            }
            return true;
        };

        var checkAccess = function (deviceAccessArr, ua) {
            var uaObj = useragent.lookup(ua);
            //if (uaObj && uaObj.family && uaObj.os && uaObj.os.family) {
            if (uaObj && uaObj.family) {
                var check = deviceAccessArr.some(function (da) {
                    if (!da) {
                        return false;
                    }
                    if (da.family && da.family !== '*') {
                        if (da.family.trim().toUpperCase() !== uaObj.family.trim().toUpperCase()) {
                            return false;
                        }
                    }
                    if (da.os && da.os !== '*') {
	                      if(uaObj.os && uaObj.os.family){
	                        if (uaObj.os.family.trim().toUpperCase().indexOf(da.os.family.trim().toUpperCase()) === -1) {
	                            return false;
	                        }
	                        if (!validateField('major', uaObj.os, da.os)) {
	                            return false;
	                        }
	                        if (!validateField('minor', uaObj.os, da.os)) {
	                            return false;
	                        }
	                        if (!validateField('patch', uaObj.os, da.os)) {
	                            return false;
	                        }
	                      }
	                      else{
		                      return false;
	                      }
                    }
                    if (!validateField('major', uaObj, da)) {
                        return false;
                    }
                    if (!validateField('minor', uaObj, da)) {
                        return false;
                    }
                    if (!validateField('patch', uaObj, da)) {
                        return false;
                    }
                    return true;
                });
                return check;
            }
        };

        if (clientUA && deviceAccess && deviceAccess.deny && Array.isArray(deviceAccess.deny)) {
            var denied = checkAccess(deviceAccess.deny, clientUA);
            if (denied) {
                return cb(156);
            }
        }

        if (clientUA && deviceAccess && deviceAccess.allow && Array.isArray(deviceAccess.allow)) {
            var allowed = checkAccess(deviceAccess.allow, clientUA);
            if (!allowed) {
                return cb(156);
            }
        }

        return cb(null, obj);
    }

    /**
     *
     * @param obj
     * @param cb
     * @returns {*}
     */
    function sessionCheck(obj, cb) {
        var mtSessionParam = {
            'session': obj.req.session,
            'tenant': {'id': obj.keyObj.tenant.id, 'key': obj.keyObj.key, 'extKey': obj.keyObj.extKey},
            'product': {
                'product': obj.keyObj.application.product,
                'package': obj.keyObj.application.package,
                'appId': obj.keyObj.application.appId
            },
            'request': {'service': obj.app.soajs.param.serviceName, 'api': obj.req.path},
            'device': obj.device,
            'geo': obj.geo,
            'req': obj.req
        };
        var mtSession = new MultiTenantSession(mtSessionParam);
        obj.req.soajs.session = mtSession;
        return cb(null, obj);
    }

    /**
     *
     * @param obj
     * @param cb
     * @returns {*}
     */
    function uracCheck(obj, cb) {
        var userServiceConf = {};
        if (obj.req.soajs.session)
            userServiceConf = obj.req.soajs.session.getConfig();
        var tenantServiceConf = obj.keyObj.config;
        obj.req.soajs.servicesConfig = merge.recursive(true, tenantServiceConf, userServiceConf);
        return cb(null, obj);
    }

    /**
     *
     * @param obj
     * @param cb
     * @returns {*}
     */
    function apiCheck(obj, cb) {
        var system = _system.getAcl(obj);
        var api = (system && system.apis ? system.apis[obj.req.path] : null);
        if (!api && system && system.apisRegExp && Object.keys(system.apisRegExp).length) {
            for (var jj = 0; jj < system.apisRegExp.length; jj++) {
                if (system.apisRegExp[jj].regExp && obj.req.path.match(system.apisRegExp[jj].regExp)) {
                    api = system.apisRegExp[jj];
                }
            }
        }
        var apiRes = null;
        if (system && system.access) {
            if (_urac.getUser(obj.req)) {
                if (system.access instanceof Array) {
                    var checkAPI = false;
                    var userGroups = _urac.getGroups(obj.req);
                    if (userGroups) {
                        for (var ii = 0; ii < userGroups.length; ii++) {
                            if (system.access.indexOf(userGroups[ii]) !== -1)
                                checkAPI = true;
                        }
                    }
                    if (!checkAPI)
                        return cb(157);
                }
            } else {
                if (!api || api.access)
                    return cb(158);
            }
            apiRes = _api.checkPermission(system, obj.req, api);
            if (apiRes.result)
                return cb(null, obj);
            else
                return cb(apiRes.error);
        }
        if (api || (system && ('restricted' === system.apisPermission))) {
            apiRes = _api.checkPermission(system, obj.req, api);
            if (apiRes.result)
                return cb(null, obj);
            else
                return cb(apiRes.error);
        }
        else
            return cb(null, obj);
    }

    /**
     *
     * @param obj
     * @param cb
     */
    function persistSession(obj, cb) {
        obj.req.sessionStore.set(obj.req.sessionID, obj.req.session, function (err, data) {
            if (err) {
                obj.req.soajs.log.error(err);
                return cb(163);
            }
            core.security.authorization.set(obj.res, obj.req.sessionID);
            return cb(null, obj);
        });
    }

    /**
     *
     * @type {{getAcl: "getAcl"}}
     * @private
     */
    var _system = {
        "getAcl": function (obj) {
            var aclObj = null;
            if (obj.req.soajs.session) {
                var uracACL = obj.req.soajs.session.getAcl();
                if (uracACL)
                    aclObj = uracACL[obj.app.soajs.param.serviceName];
            }
            if (!aclObj && obj.keyObj.application.acl) {
                aclObj = obj.keyObj.application.acl[obj.app.soajs.param.serviceName];
            }
            if (!aclObj && obj.packObj.acl)
                aclObj = obj.packObj.acl[obj.app.soajs.param.serviceName];

            if (aclObj && (aclObj.apis || aclObj.apisRegExp || aclObj.apisPermission))
                return aclObj;
            else {
                //ACL with method support restful
                var method = obj.req.method.toLocaleLowerCase();
                console.log ("===================== ANTO")
                console.log (aclObj)
                console.log (method)
                if (aclObj && aclObj[method] && typeof aclObj[method] === "object"){
                    var newAclObj = {};
                    if (aclObj.hasOwnProperty('access'))
                        newAclObj.access = aclObj.access;
                    if (aclObj[method].hasOwnProperty('apis'))
                        newAclObj.apis = aclObj[method].apis;
                    if (aclObj[method].hasOwnProperty('apisRegExp'))
                        newAclObj.apisRegExp = aclObj[method].apisRegExp;
                    if (aclObj[method].hasOwnProperty('apisPermission'))
                        newAclObj.apisPermission = aclObj[method].apisPermission;
                    console.log (newAclObj)
                    return newAclObj;
                }
                else
                    return aclObj;
            }
        }
    };

    /**
     *
     * @type {{getUser: "getUser", getGroups: "getGroups"}}
     * @private
     */
    var _urac = {
        "getUser": function (req) {
            var urac = null;
            if (req.soajs.session)
                urac = req.soajs.session.getUrac();
            return urac;
        },
        "getGroups": function (req) {
            var groups = null;
            if (req.soajs.session)
                groups = req.soajs.session.getGroups();
            return groups;
        }
    };

    /**
     *
     * @type {{checkPermission: "checkPermission", checkAccess: "checkAccess"}}
     * @private
     */
    var _api = {
        "checkPermission": function (system, req, api) {
            if ('restricted' === system.apisPermission) {
                if (!api)
                    return {"result": false, "error": 159};
                return _api.checkAccess(api.access, req);
            }
            if (!api)
                return {"result": true};
            return _api.checkAccess(api.access, req);
        },
        "checkAccess": function (apiAccess, req) {
            if (!apiAccess)
                return {"result": true};
            if (!_urac.getUser(req))
                return {"result": false, "error": 161};
            if (apiAccess instanceof Array) {
                var userGroups = _urac.getGroups(req);
                if (!userGroups)
                    return {"result": false, "error": 160};
                for (var ii = 0; ii < userGroups.length; ii++) {
                    if (apiAccess.indexOf(userGroups[ii]) !== -1)
                        return {"result": true};
                }
                return {"result": false, "error": 160};
            }
            else
                return {"result": true};
        }
    };

    return function (req, res, next) {
        if (req.soajs.registry.services[soajs.param.serviceName].extKeyRequired) {
            try {
                provision.getExternalKeyData(req.get("key"), req.soajs.registry.serviceConfig.key, function (err, keyObj) {
                    if (err)
                        req.soajs.log.warn(err);
                    if (keyObj && keyObj.application && keyObj.application.package) {
                        req.soajs.tenant = keyObj.tenant;
                        req.soajs.tenant.key = {
                            "iKey": keyObj.key,
                            "eKey": keyObj.extKey
                        };
                        req.soajs.tenant.application = keyObj.application;
                        provision.getPackageData(keyObj.application.package, function (err, packObj) {
                            if (err)
                                req.soajs.log.warn(err);
                            if (packObj) {
                                req.soajs.tenant.application.package_acl = packObj.acl;
                                req.soajs.tenant.application.package_acl_all_env = packObj.acl_all_env;
                                var serviceCheckArray = [function (cb) {
                                    cb(null, {"app": app, "res": res, "req": req, "keyObj": keyObj, "packObj": packObj});
                                }];

                                if (!param.session && param.multitenant)
                                    serviceCheckArray.push(serviceCheck);

                                if (param.security) {
                                    serviceCheckArray.push(securityGeoCheck);
                                    serviceCheckArray.push(securityDeviceCheck);
                                }

                                if (param.session)
                                    serviceCheckArray.push(sessionCheck);

                                if (param.multitenant) {
                                    serviceCheckArray.push(uracCheck);
                                    if (param.session)
                                        serviceCheckArray.push(serviceCheck);
                                }

                                if (param.multitenant && param.acl)
                                    serviceCheckArray.push(apiCheck);

                                if (param.session)
                                    serviceCheckArray.push(persistSession);

                                async.waterfall(serviceCheckArray, function (err, data) {
                                    if (err)
                                        return next(err);
                                    else
                                        return next();
                                });
                            }
                            else
                                return next(152);
                        });
                    }
                    else
                        return next(153);
                });
            } catch (err) {
                req.soajs.log.error(150, err.stack);
                res.jsonp(req.soajs.buildResponse(core.error.getError(150)));
            }
        }
        else {
            return next();
        }
    };
};
<commit_msg>removed unneeded logs<commit_after>'use strict';

var core = require('../../modules/soajs.core');
var provision = require("../../modules/soajs.provision");
var MultiTenantSession = require("../../classes/MultiTenantSession");
var async = require("async");
var Netmask = require('netmask').Netmask;
var useragent = require('useragent');
var merge = require('merge');

/**
 *
 * @param configuration
 * @returns {Function}
 */
module.exports = function (configuration) {
    var soajs = configuration.soajs;
    var param = configuration.param;
    var app = configuration.app;

    /**
     *
     * @param obj
     * @param cb
     * @returns {*}
     */
    function serviceCheck(obj, cb) {
        var system = _system.getAcl(obj);
        if (system)
            return cb(null, obj);
        else
            return cb(154);
    }

    /**
     *
     * @param obj
     * @param cb
     * @returns {*}
     */
    function securityGeoCheck(obj, cb) {
        var clientIp = obj.req.getClientIP();
        var geoAccess = obj.keyObj.geo; //{"allow": ["127.0.0.1"], "deny": []};
        obj.geo = {"ip": clientIp};

        var checkAccess = function (geoAccessArr, ip) {
            var check = geoAccessArr.some(function (addr) {
                try {
                    var block = new Netmask(addr);
                    return block.contains(ip);
                } catch (err) {
                    obj.req.soajs.log.error('Geographic security configuration failed: ', addr);
                    obj.req.soajs.log.error(err);
                }
                return false;
            });
            return check;
        };

        if (clientIp && geoAccess && geoAccess.deny && Array.isArray(geoAccess.deny)) {
            var denied = checkAccess(geoAccess.deny, clientIp);
            if (denied)
                return cb(155);
        }

        if (clientIp && geoAccess && geoAccess.allow && Array.isArray(geoAccess.allow)) {
            var allowed = checkAccess(geoAccess.allow, clientIp);
            if (!allowed)
                return cb(155);
        }

        return cb(null, obj);
    }

    /**
     *
     * @param obj
     * @param cb
     * @returns {*}
     */
    function securityDeviceCheck(obj, cb) {
        var clientUA = obj.req.getClientUserAgent();
        var deviceAccess = obj.keyObj.device; //{"allow": [{"family": "chrome"}], "deny": []};
        obj.device = clientUA;

        var validateField = function (fieldName, uaObj, da) {
            if (da[fieldName] && da[fieldName] !== '*' && uaObj[fieldName]) {
                if (typeof (da[fieldName]) === 'string') {
                    if (da[fieldName].trim().toUpperCase() !== uaObj[fieldName].trim().toUpperCase()) {
                        return false;
                    }
                    if (da[fieldName].min) {
                        if (da[fieldName].min.trim() > uaObj[fieldName].trim()) {
                            return false;
                        }
                    }
                }
                if (da[fieldName].max) {
                    if (da[fieldName].max.trim() < uaObj[fieldName].trim()) {
                        return false;
                    }
                }
            }
            return true;
        };

        var checkAccess = function (deviceAccessArr, ua) {
            var uaObj = useragent.lookup(ua);
            //if (uaObj && uaObj.family && uaObj.os && uaObj.os.family) {
            if (uaObj && uaObj.family) {
                var check = deviceAccessArr.some(function (da) {
                    if (!da) {
                        return false;
                    }
                    if (da.family && da.family !== '*') {
                        if (da.family.trim().toUpperCase() !== uaObj.family.trim().toUpperCase()) {
                            return false;
                        }
                    }
                    if (da.os && da.os !== '*') {
	                      if(uaObj.os && uaObj.os.family){
	                        if (uaObj.os.family.trim().toUpperCase().indexOf(da.os.family.trim().toUpperCase()) === -1) {
	                            return false;
	                        }
	                        if (!validateField('major', uaObj.os, da.os)) {
	                            return false;
	                        }
	                        if (!validateField('minor', uaObj.os, da.os)) {
	                            return false;
	                        }
	                        if (!validateField('patch', uaObj.os, da.os)) {
	                            return false;
	                        }
	                      }
	                      else{
		                      return false;
	                      }
                    }
                    if (!validateField('major', uaObj, da)) {
                        return false;
                    }
                    if (!validateField('minor', uaObj, da)) {
                        return false;
                    }
                    if (!validateField('patch', uaObj, da)) {
                        return false;
                    }
                    return true;
                });
                return check;
            }
        };

        if (clientUA && deviceAccess && deviceAccess.deny && Array.isArray(deviceAccess.deny)) {
            var denied = checkAccess(deviceAccess.deny, clientUA);
            if (denied) {
                return cb(156);
            }
        }

        if (clientUA && deviceAccess && deviceAccess.allow && Array.isArray(deviceAccess.allow)) {
            var allowed = checkAccess(deviceAccess.allow, clientUA);
            if (!allowed) {
                return cb(156);
            }
        }

        return cb(null, obj);
    }

    /**
     *
     * @param obj
     * @param cb
     * @returns {*}
     */
    function sessionCheck(obj, cb) {
        var mtSessionParam = {
            'session': obj.req.session,
            'tenant': {'id': obj.keyObj.tenant.id, 'key': obj.keyObj.key, 'extKey': obj.keyObj.extKey},
            'product': {
                'product': obj.keyObj.application.product,
                'package': obj.keyObj.application.package,
                'appId': obj.keyObj.application.appId
            },
            'request': {'service': obj.app.soajs.param.serviceName, 'api': obj.req.path},
            'device': obj.device,
            'geo': obj.geo,
            'req': obj.req
        };
        var mtSession = new MultiTenantSession(mtSessionParam);
        obj.req.soajs.session = mtSession;
        return cb(null, obj);
    }

    /**
     *
     * @param obj
     * @param cb
     * @returns {*}
     */
    function uracCheck(obj, cb) {
        var userServiceConf = {};
        if (obj.req.soajs.session)
            userServiceConf = obj.req.soajs.session.getConfig();
        var tenantServiceConf = obj.keyObj.config;
        obj.req.soajs.servicesConfig = merge.recursive(true, tenantServiceConf, userServiceConf);
        return cb(null, obj);
    }

    /**
     *
     * @param obj
     * @param cb
     * @returns {*}
     */
    function apiCheck(obj, cb) {
        var system = _system.getAcl(obj);
        var api = (system && system.apis ? system.apis[obj.req.path] : null);
        if (!api && system && system.apisRegExp && Object.keys(system.apisRegExp).length) {
            for (var jj = 0; jj < system.apisRegExp.length; jj++) {
                if (system.apisRegExp[jj].regExp && obj.req.path.match(system.apisRegExp[jj].regExp)) {
                    api = system.apisRegExp[jj];
                }
            }
        }
        var apiRes = null;
        if (system && system.access) {
            if (_urac.getUser(obj.req)) {
                if (system.access instanceof Array) {
                    var checkAPI = false;
                    var userGroups = _urac.getGroups(obj.req);
                    if (userGroups) {
                        for (var ii = 0; ii < userGroups.length; ii++) {
                            if (system.access.indexOf(userGroups[ii]) !== -1)
                                checkAPI = true;
                        }
                    }
                    if (!checkAPI)
                        return cb(157);
                }
            } else {
                if (!api || api.access)
                    return cb(158);
            }
            apiRes = _api.checkPermission(system, obj.req, api);
            if (apiRes.result)
                return cb(null, obj);
            else
                return cb(apiRes.error);
        }
        if (api || (system && ('restricted' === system.apisPermission))) {
            apiRes = _api.checkPermission(system, obj.req, api);
            if (apiRes.result)
                return cb(null, obj);
            else
                return cb(apiRes.error);
        }
        else
            return cb(null, obj);
    }

    /**
     *
     * @param obj
     * @param cb
     */
    function persistSession(obj, cb) {
        obj.req.sessionStore.set(obj.req.sessionID, obj.req.session, function (err, data) {
            if (err) {
                obj.req.soajs.log.error(err);
                return cb(163);
            }
            core.security.authorization.set(obj.res, obj.req.sessionID);
            return cb(null, obj);
        });
    }

    /**
     *
     * @type {{getAcl: "getAcl"}}
     * @private
     */
    var _system = {
        "getAcl": function (obj) {
            var aclObj = null;
            if (obj.req.soajs.session) {
                var uracACL = obj.req.soajs.session.getAcl();
                if (uracACL)
                    aclObj = uracACL[obj.app.soajs.param.serviceName];
            }
            if (!aclObj && obj.keyObj.application.acl) {
                aclObj = obj.keyObj.application.acl[obj.app.soajs.param.serviceName];
            }
            if (!aclObj && obj.packObj.acl)
                aclObj = obj.packObj.acl[obj.app.soajs.param.serviceName];

            if (aclObj && (aclObj.apis || aclObj.apisRegExp || aclObj.apisPermission))
                return aclObj;
            else {
                //ACL with method support restful
                var method = obj.req.method.toLocaleLowerCase();
                if (aclObj && aclObj[method] && typeof aclObj[method] === "object"){
                    var newAclObj = {};
                    if (aclObj.hasOwnProperty('access'))
                        newAclObj.access = aclObj.access;
                    if (aclObj[method].hasOwnProperty('apis'))
                        newAclObj.apis = aclObj[method].apis;
                    if (aclObj[method].hasOwnProperty('apisRegExp'))
                        newAclObj.apisRegExp = aclObj[method].apisRegExp;
                    if (aclObj[method].hasOwnProperty('apisPermission'))
                        newAclObj.apisPermission = aclObj[method].apisPermission;
                    return newAclObj;
                }
                else
                    return aclObj;
            }
        }
    };

    /**
     *
     * @type {{getUser: "getUser", getGroups: "getGroups"}}
     * @private
     */
    var _urac = {
        "getUser": function (req) {
            var urac = null;
            if (req.soajs.session)
                urac = req.soajs.session.getUrac();
            return urac;
        },
        "getGroups": function (req) {
            var groups = null;
            if (req.soajs.session)
                groups = req.soajs.session.getGroups();
            return groups;
        }
    };

    /**
     *
     * @type {{checkPermission: "checkPermission", checkAccess: "checkAccess"}}
     * @private
     */
    var _api = {
        "checkPermission": function (system, req, api) {
            if ('restricted' === system.apisPermission) {
                if (!api)
                    return {"result": false, "error": 159};
                return _api.checkAccess(api.access, req);
            }
            if (!api)
                return {"result": true};
            return _api.checkAccess(api.access, req);
        },
        "checkAccess": function (apiAccess, req) {
            if (!apiAccess)
                return {"result": true};
            if (!_urac.getUser(req))
                return {"result": false, "error": 161};
            if (apiAccess instanceof Array) {
                var userGroups = _urac.getGroups(req);
                if (!userGroups)
                    return {"result": false, "error": 160};
                for (var ii = 0; ii < userGroups.length; ii++) {
                    if (apiAccess.indexOf(userGroups[ii]) !== -1)
                        return {"result": true};
                }
                return {"result": false, "error": 160};
            }
            else
                return {"result": true};
        }
    };

    return function (req, res, next) {
        if (req.soajs.registry.services[soajs.param.serviceName].extKeyRequired) {
            try {
                provision.getExternalKeyData(req.get("key"), req.soajs.registry.serviceConfig.key, function (err, keyObj) {
                    if (err)
                        req.soajs.log.warn(err);
                    if (keyObj && keyObj.application && keyObj.application.package) {
                        req.soajs.tenant = keyObj.tenant;
                        req.soajs.tenant.key = {
                            "iKey": keyObj.key,
                            "eKey": keyObj.extKey
                        };
                        req.soajs.tenant.application = keyObj.application;
                        provision.getPackageData(keyObj.application.package, function (err, packObj) {
                            if (err)
                                req.soajs.log.warn(err);
                            if (packObj) {
                                req.soajs.tenant.application.package_acl = packObj.acl;
                                req.soajs.tenant.application.package_acl_all_env = packObj.acl_all_env;
                                var serviceCheckArray = [function (cb) {
                                    cb(null, {"app": app, "res": res, "req": req, "keyObj": keyObj, "packObj": packObj});
                                }];

                                if (!param.session && param.multitenant)
                                    serviceCheckArray.push(serviceCheck);

                                if (param.security) {
                                    serviceCheckArray.push(securityGeoCheck);
                                    serviceCheckArray.push(securityDeviceCheck);
                                }

                                if (param.session)
                                    serviceCheckArray.push(sessionCheck);

                                if (param.multitenant) {
                                    serviceCheckArray.push(uracCheck);
                                    if (param.session)
                                        serviceCheckArray.push(serviceCheck);
                                }

                                if (param.multitenant && param.acl)
                                    serviceCheckArray.push(apiCheck);

                                if (param.session)
                                    serviceCheckArray.push(persistSession);

                                async.waterfall(serviceCheckArray, function (err, data) {
                                    if (err)
                                        return next(err);
                                    else
                                        return next();
                                });
                            }
                            else
                                return next(152);
                        });
                    }
                    else
                        return next(153);
                });
            } catch (err) {
                req.soajs.log.error(150, err.stack);
                res.jsonp(req.soajs.buildResponse(core.error.getError(150)));
            }
        }
        else {
            return next();
        }
    };
};
<|endoftext|>