Drupal highly critical vulnerability - DrupalGeddon 2 - We've got you covered

This blog post attempts to focus on the highly critical vulnerability that was announced by Drupal on 28th March tagged as SA-CORE-2018–002, Drupalgeddon 2.

Recently, Drupal core announced a security advisory rated as highly vulnerable - dubbed DrupalGeddon 2 (SA-CORE-2018-002 / CVE-2018-7600) - that has the potential to affect the vast majority of Drupal 6, 7 and 8 websites.

According to BuiltWith, around 9% of websites are running on Drupal and hence had a high probability of being affected by the vulnerability as the score is 24/25.

SA-CORE-2018-002 potentially allow attackers to take full control of any affected Drupal site that could result in the site being completely compromised. The vulnerability was initially scored 22/25 but was later raised to 24/25 as there were proofs of automated attacks in the wild.

The risk metrics for this vulnerability are as follows AC:None / A:None/ CI:All / II:All / E:Exploit / TD:Default. You can read the article about security risk levels to know more about the details of the risk metrics. In short, SA-CORE-2018-002 means:

  • AC (Access Complexity): None - It is very easy for the attacker to leverage the vulnerability.
  • A (Authentication): None - No privilege level was required for the exploit to be successful. Meaning even anonymous users could exploit the vulnerability.
  • CI (Confidentiality impact): All - All non-public data was accessible because of the vulnerability.
  • II (Integrity impact): All - The data could have been easily modified or deleted.
  • E (Exploit) - An exploit is known to exist or is documented.
  • TD (Target distribution): Default - The default configurations were likely to be affected.

If you are curious to know how the score (24/25) was obtained you can take a look at Risk Calculator. This calculator takes six different metrics, which can have three different values. This gives an objective sense of the risk of different issues. While the numeric value gives you a sense of how critical the issue is. The security risk string, for example, “AC:None/A:None/CI:All/II:All/E:Exploit/TD:Default”, gives you a sense of six different risk factors that are considered in this case. This provides a better sense of how vulnerable your site is. Also, you are the right person to evaluate since you know how your website is structured and built, and how vulnerable it is to these specific risk factors. 

FYI, SA-CORE-2018–002 is as critical as “DrupalGeddon” episode which came to light in October 2014. To put things in perspective since 6th August 2014 (the date when NIST Common Misuse Scoring System - NISTIR 7864 was used by Drupal) there have been only three highly critical issues that have had a score of more than 23. 

Our approach

In response to this latest vulnerability, we gathered our development team to make sure we can deploy patches to this vulnerability for all our clients’ websites. We implemented a standard plan to notify all clients about the security update and to execute it across all of our supported sites immediately.

So when the patch - 8.5.1 / 8.4.6 / 8.3.9 / 7.58 - was available, our team knew exactly what to do. Just to let you know, the security update was carried out successfully as quickly as possible. Thanks to our team, at Valuebound, who worked tirelessly to ensure that all our clients’ websites were patched within hours.

If you are interested to know more how Valuebound can help you with security and maintenance of your Drupal website, do explore our services.

Read more at FAQ on SA-CORE-2018-002.

Creating a list of Steemit Profiles from steem handles

This is the third tutorial in the series Learning to play with SteemJS. In this tutorial we will learn how to fetch the profile details of the users from Steem blockchain once we have their steem handles.

preview-steemit-profile-listing-using-steemjs.png

What will you learn?

In this tutorial you will learn

  • How to use SteemJS
  • How to use steem.api.getAccounts(usernames, function(err, result) { function to fetch the details of steem user.
  • Create a basic HTML that will list the steem users' profile details in a list.
  • How to use the browsers copy to clipboard feature in Javascript.

Requirements

These are good to have requirements. Even if you don't know these you can still read the tutorial and make sense out of it.

  • Basics of HTML
  • Basics of Javascript

Difficulty

  • Basic. You can take a look at the code even if you are not from a development background. I will be happy to answer any queries you have in the comments section.

Create a HTML skeleton

    <div class="container">
      <h1>Steem Profile List Builder</h1>
      <div class="row">
        <div class="col-xs-18 col-md-9 left-region">
          <div class="row">
            <div>
                  Enter the list of user accounts whose profile details you need to fetch.
            </div>
            <textarea id="handles" rows="4" style="min-width: 100%">@gokulnk, @dragosroua, @barrydutton, @lexiconical</textarea>
            <div class="btn-group">
              <button type="button" class="btn btn-primary" id="fetch-profile">Fetch Profile Details</button>
              <button type="button" class="btn btn-primary" id="copy-html">Copy HTML</button>
            </div>
          </div>
          <div class="row" id="profile-details-html"></div>
          <div class="row" id="profile-details"></div>
        </div>
        <div class="col-xs-6 col-md-3 right-region">
          Follow <a href="https://www.steemit.com/@gokulnk" target="_blank">@gokulnk</a> for further updates.
        </div>
      </div>
    </div>
  </body>

We have created a basic layout using the Twitter Bootstrap library. You can learn more about the Bootstrap layouts and grids from here. We have created a text area input field along with two buttons one from generating the html and the other for copying the html.

We have also created two empty divs <div class="row" id="profile-details-html"></div> <div class="row" id="profile-details"></div>which will store the sample perview and the html code once the user clickcs on the button.

Add relevant javascript files

In your head tag add the following scripts

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
    <script src="https://cdn.steemjs.com/lib/latest/steem.min.js"></script>

The first script is the jQuery library file which simplifies DOM manipulations and saves time in performing the frequently used actions in javascript. We will use these two files in all the browser based tutorials going forward.

The second script is the minified version of Bootstrap library which will help created the basic grids and makes sure that we can reuse the css elements from bootstrap library. In this case we have used this for creating grid, create button groups and making the input fields full width. We can do most of this by adding relevant classes to the html elements that we already use.

The third script is the minified version of SteemJS library which will help us interact with the steem blockchain direction from the javascript/browser.

Getting the inputs and sanitising the data

    $('#fetch-profile').click(function(){
      $('#profile-details').text("Fetching the details from Steem Blockchain");
      $('#profile-details-html-textarea').text();
      markDownHolder = "";
      handles = $('#handles').val();
      usernames = handles.replace(new RegExp("@", "g"),"").replace(new RegExp(" ", "g"),"").split(",");

In the above code on click of the submit button we are clearing the contents of our placeholder divs and adding relevant messages. We are doing this to make sure that even if the user clicks on submit button after fetching the output, it should still work as expected. We are cleaning up the input from the text area to remove unnecessary spaces and converting it into an array of steem handles that can be passed to the next function.

Understanding steem.api.getAccounts function

The takeaway from this tutorial will be how to use steem.api.getAccounts function. We pass the array of usernames to the function as the first parameter and second parameter is the handling function. If there is an error we are printing it to the console. If there is no error then we are processing it to display the output.

        steem.api.getAccounts(usernames, function(err, result) {
          if (err) {
            console.log(err);
          }else{
            $('#profile-details').text("");
            $('#profile-details-html').html('<textarea id="profile-details-html-textarea" rows="4" style="min-width: 100%">Filling HTML</textarea>');
            result.forEach(function(userAccount, i){
              console.log(getProfileHTML(userAccount));
              profileDetails = getProfileHTML(userAccount, i);
              markDownHolder += profileDetails;
            });
          $('#profile-details-html-textarea').html(markDownHolder);
         $('#profile-details').html('<h4>Preview (Looks much better in Steemit)</h3>' + markDownHolder);
}

In this code we are doing a couple of things. We are calling the function steem.api.getAccounts and once we have the details of the users we are looping through the results and concatenating the processed output of the users. Then we are populating the Preview and code text area with the processed output.

The processing function

The processing function generates the html output for each of the user. I have just used some crude string concatenations to generate the output. It can definitely be improved.

function getProfileHTML(userAccount, i){
  profile = JSON.parse(userAccount.json_metadata).profile;
  divBgColor = i % 2 == 0 ? "#FEFEFE" : "EDEDED";
  console.log(userAccount);
  console.log(profile);
  profileImage = profile.profile_image || defaultImage;
  profileTargetUrl = steemAuthorFullurl(userAccount.name);
  profileHTML = `<div style="clear:left"></div><div style="width:100%;height: 100%;border:red 1px;background-color=${divBgColor};padding=2px"><div class="profile-image" style="float:left;display:inline-block;width: 100px;height: 100%;"><a href="/%24%7BprofileTargetUrl%7D"><img width = "90px" height = "90px" src="/%24%7BprofileImage%7D"></a></div><div class="profile-details" style="float:left;display:inline-block;width: -moz-calc(100% - 100px);width: -webkit-calc(100% - 100px);width: calc(100% - 100px);height: 100%;">${profile.name || ""}(${userAccount.name || ""})<br/>${profile.about || ""}</div></div>`;
  //divPullClass = i % 2 == 0 ? "pull-right" : "pull-left";
  divPullClass = "pull-left";
  profileSteemHTML = `<div class="${divPullClass}"><a href="/%24%7BprofileTargetUrl%7D" target="_blank"><img src="https://steemitimages.com/100x100/${profileImage}"></a></div><b>${profile.name || ""} (<a href="/%24%7BprofileTargetUrl%7D" target="_blank">${userAccount.name}</a>)</b><br/>${profile.about || ""}<hr/>\n\n`;
  return profileSteemHTML;
}

Following Helper functions are used to generate links to the authors and blogs.

  function steemBlogFullurl(author, permlink) {
      return BASEURL + '@' + author + '/' + permlink;
  }
  function steemBlogFullurl(author, permlink) {
      return BASEURL + '@' + author + '/' + permlink;
  }
  function steemAuthorFullurl(author) {
      return BASEURL + '@' + author;
  }
  function steemAuthorLink(author) {
    return getLink('@' + author, steemAuthorFullurl(author));
  }
  function getLink(linkText, targetLink) {
    if (typeof linkText == "undefined" || linkText == ''){
      linkText = targetLink;
    }else if (typeof targetLink === "undefined") {
      targetLink = linkText;
    }
    return `<a href = ${targetLink} target="_blank">${linkText}</a>`;
  }

Final notes.

You can checkout the final code and the demo to see what you have created with the help of this tutorial.

Originally published on https://steemit.com/utopian-io/@gokulnk/creating-a-list-of-steemit-prof…

Safety concerns in an E-Commerce site and how Drupal is addressing it

The advances in technology has brought in an unprecedented growth in E-Commerce industry, which has become a major target for cyber crimes. It becomes necessary to address the security measures for websites as any data breach leads to the loss of sensitive information along with monetary losses. This not only threatens reputation of the organization but also leads to mistrust among customers. When compared to leading organizations, smaller firms are affected more as they have to suffer substantial losses.

Full security over the web can’t be attained as the hackers are devising new plans everyday to access consumer data. But, threats can be minimised by following certain security measures.

Based on our experience of working on several E-Commerce websites built using Drupal framework, in this article, we will talk about various safety parameters and how these risks can be addressed.

Sensitive Data Exposure

The PCI DSS  recommends that an E-Commerce application shouldn’t store unnecessary consumer information as it may be prone to cyber attacks. Such information should be stored in a confidential manner, using strong encryptions.

In Drupal, the stored account passwords are protected and hashed based on Portable PHP Password Hashing Framework. The Drupal community-contributed codes offer solutions to encrypt sensitive data, whether stationary or in circulation.

XSS (Cross-site Scripting)

The XSS attacks are a type of injection, where infected scripts are injected into trusted websites. When these scripts are received by browsers, it  leads to data breach.

By default, any untrusted user's content is filtered to remove dangerous elements in Drupal Core. In case any anonymous content is identified, the errors which can lead to XSS vulnerabilities can be mitigated by building safer defaults.

Weak Access Control

The end users can’t be given the kind of access that administrators  have over their site. This is concealed using certain Java Scripts. If these Java Scripts become accessible to all, data can be easily breached. Additional security measures like two factor authentication through OTPs and e-mails should also be implemented to limit such kind of access.

Access controls in Drupal are protected by a powerful permission-based system which checks for proper authorization before any action is taken. With a number of modules, access checking can be tightly integrated into the entire menu-rendering and routing system. This enables the protection of visibility of navigation links and pages by the same system that handles incoming requests.

Security Misconfiguration

Although the contemporary E-Commerce applications come with an extra layer of security, but any loophole in the configuration can make them vulnerable. 

Inefficiencies that lead to misconfiguration are corrected through usability testing and fixes that are recommended for inclusion to Drupal core. There are several contributed projects that conduct automated security review or implement further secure configurations.

Broken Authentication and Session Management

Almost every webpage users use, caches their data and links a unique session ID with them while displaying the result they seek. If they copy and share the URL of the website with another individual, they also accidentally end up giving their session ID. If it is replicated, hackers can easily get into users’ session and access their information.

User accounts and authentication are managed by Drupal core on the server to prevent a user from escalating authorisation. The passwords are hashed using PHP framework and existing sessions are destroyed upon login and logout.

Unvalidated Redirects and Forwards

It is advisable for users to go for only authenticated redirects and certified links present in the comments section of a web page. This is because unauthenticated redirects  and links can lead you to a malicious page, created by an attacker to get the access to important administrative functions of the webpage.

Internal page redirects cannot be used to circumvent Drupal's integrated menu and access control system. Drupal protects a site against automatic redirection via anonymous links to off-site URLs which could be used in a phishing attack.

Security is an essential part of E-Commerce development and should be one of the fundamental objectives that needs to be kept in mind. It should be a part of development practice from project planning stage itself. If you are using Drupal to build your E-Commerce platform, it is as secured  as any other pure E-Commerce enterprise framework available in market. And in new age of commerce where content and community are part of your marketing effort, Drupal scores over most of different options available. Just to substantiate, one of the leading enterprise commerce framework, Magento Commerce site itself runs on Drupal. 

If you are building an E-Commerce site using Drupal and need assistance, please do contact us.

Using SteemSQL to query Steem database in your SteemJS Application

SteemJS is still rudimentary and if you start developing some applications you will know that they will fall short. For a bot that I was working on I wanted to know if the user has already posted earlier with the same tag. The case in questions was I wanted to check if the user is misusing the #introduceyourself tag. So before posting a welcome message to the users I wanted to check if he has created more than two posts with the#introduceyourself tag.

What will you learn?

In this tutorial you will learn

  • How to use SteemSQL in SteemJS code
  • How to use steem.api.streamTransaction function to do something when a user has created a post.
  • Using SteemSQL to identify if the user has already create posts with a similar tag.

Requirements

These are good to have requirements. Even if you don't know these you can still read the tutorial and make sense out of it.

  • Basics of Javascript
  • Basics of SteemJS

Difficulty

  • Advanced. You can take a look at the code even if you are not at an advanced level. It might seem a little complicated but it will start making sense to once you cover your basics. I will be happy to answer any queries you have in the comments section.

Add relevant node packages and settings.

In the below script we are adding relevant node packages and their related settings.

We are adding steem package so that we can use steemJS APIs. We are setting that url to wss://steemd-int.steemit.com which is functioning without any issues for me for last two months. We are settings up variables that will be used across the file.

We are adding mssql package as SteemSQL is a MS-SQL database. You can get your SteemSQL credentials by purchasing the subscription as mentioned in the post

var steem = require('steem');
steem.api.setOptions({ url: 'wss://steemd-int.steemit.com' });


const BASEURL = 'https://steemit.com/'
const ACCOUNT_NAME = 'steemladder'

console.log('SteemLadder app has started');

const sql = require('mssql');
const config = {
    user: 'Steemit-gokulnk',
    password: 'you-will-get-this-once-you-subscribe',
    server: 'vip.steemsql.com',
    database: 'DBSteem',
}

Listem to streamTransaction to identify when a comment is posted.

In the below script we are listening streamOperations. Once the streamOperation is emmitted we are getting the txType and txData from the operation. We are then checking if the txType is comment and it has no parent(comments without parents or posts) and has metadata. If it passes all these conditions they we get the tags of the posts from metadata and see if the tags text contains the tags we are looking for.

steem.api.streamOperations(function (err, operations) {
    var txType = operations[0];
    var txData = operations[1];
    var steemDbquery = '';
    if (txType == 'comment' && txData.parent_author == '' &&  txData.json_metadata){
        var metadata = JSON.parse(txData.json_metadata);
        if (metadata) {
            var tags = metadata.tags || [];
            var parentAuthor = txData.author;
            var parentPermlink = txData.permlink;
            var commentPermlink = steem.formatter.commentPermlink(parentAuthor, parentPermlink);

            if (tags.indexOf("introduceyourself") > -1) {

Once it matches all these we now need to check if the user has already posted earlier with the same tag.

Use SteemSQL before running doSomething function

This is the core of the tutorial and we will see how to use the SteemSQL query in steemJS.

In the code below we are checking that the json_metadata contains the work introduce and depth is 0 to make sure that we are querying only the posts and not the comments. Since node.js is asynchronous we will get the response from the DB and we need to use then to process that output. Within the the then function we are checking if we have got more than 2 rows which satisfies our conditions. Including the current post if the user has posted less than or equal to two posts with #introduce tags then we can perform some action like say up-voting their posts.

                    steemDbquery = `SELECT * FROM [dbo].[Comments] where author = '${parentAuthor}' AND json_metadata like '%introduce%' AND DEPTH = 0`;
                    sql.connect(config).then(pool => {
                        console.log('Connected to SteemSQL');
                        return pool.request()
                            .query(steemDbquery)
                    }).then(result => {
                        console.log(result); // Print SQL results to console for debugging                                                                                           
                        if (result.rowsAffected[0] <=2) {
                            doSomething();
                        }
                        sql.close();
                    })

                    sql.on('error', err => {
                        console.log('Unable to connect to DB');
                    })

Helper Functions

Following Helper functions are used to generate links to the authors and blogs.

  function steemBlogFullurl(author, permlink) {
      return BASEURL + '@' + author + '/' + permlink;
  }
  function steemBlogFullurl(author, permlink) {
      return BASEURL + '@' + author + '/' + permlink;
  }
  function steemAuthorFullurl(author) {
      return BASEURL + '@' + author;
  }
  function steemAuthorLink(author) {
    return getLink('@' + author, steemAuthorFullurl(author));
  }
  function getLink(linkText, targetLink) {
    if (typeof linkText == "undefined" || linkText == ''){
      linkText = targetLink;
    }else if (typeof targetLink === "undefined") {
      targetLink = linkText;
    }
    return `<a href = ${targetLink} target="_blank">${linkText}</a>`;
  }

Final notes.

You can checkout the final code from Github.

Curriculum

If you are a developer and would like to kickcstart your learning you can check the following link to set up your dev environments and tools. As I write further tutorials I will add them to the list.

Originally published on https://steemit.com/utopian-io/@gokulnk/using-steemsql-to-query-steem-d…

Build matrix like Steem Stream with SteemJs

This is going to be the first tutorial in the tutorial series I will be starting. I am working on a couple of Steem projects and I will share my learnings from the project as Tutorial Series. This tutorial intends to be the "Hello World" program of coding on Steem Blockchain. In this tutorial we will create a simple activity stream which shows the latest activity on the blockchain. To make things a little interesting I will format it in the Matrix style. You will know what I mean once you look at the demo. If you just want to take sneak peak at what we will be achieving before starting the tutorial take a look at https://nkgokul.github.io/steem-tutorials/SteemStream.html

matrix.jpg

What will you learn?

In this tutorial you will learn

  • How to use SteemJS
  • How to use steem.api.streamTransaction function to check for transactions from the latest blocks.
  • Create a basic HTML that will display the steem stream in a matrix like fashion.

Requirements

These are good to have requirements. Even if you don't know these you can still read the tutorial and make sense out of it.

  • Basics of HTML
  • Basics of Javascript

Difficulty

  • Basic. You can take a look at the code even if you are not from a development background. I will be happy to answer any queries you have in the comments section.

Create a HTML skeleton

<body>
  <div id="gokul-details">
    <h3>This example was created by <a href="https://www.steemit.com/@gokulnk" target="_blank">@gokulnk</a></h3>
  </div>
  <div id="steem-data-wrapper">
    <h2>Please wait while fetching the data from Steem Blockchian.</h2>
  </div>
</body>

Within the body tag create a div which we will use to populate the contents of our data stream from Steem blockchain.

Add relevant javascript files

In your head tag add the following scripts

  <script src="https://cdn.steemjs.com/lib/latest/steem.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The first script is the minified version of SteemJS library which will help us interact with the steem blockchain direction from the javascript/browser.

The second script is the jQuery library file which simplifies DOM manipulations and saves time in performing the frequently used actions in javascript. We will use these two files in all the browser based tutorials going forward.

Understanding steem.api.streamTransactions function

The takeaway from this tutorial will be how to use steem.api.streamTransactions function

  console.log('hello, is this working')
  var counter = 1;
  const BASEURL = 'https://steemit.com/'
  const ACCOUNT_NAME = 'gokulnk'
  steem.api.setOptions({ url: 'https://api.steemit.com' });
  steem.api.streamTransactions('head', function(err, result) {
    let txType = result.operations[0][0]
    let txData = result.operations[0][1]
    jQuery('#steem-data-wrapper').prepend('<div class="stream-activity' + counter + '">' + counter++ + ' ' + getMessagefromTransaction(txType, txData) + '</div>');
  }); 

In this code we are doing a couple of things.

  1. setup some variables like counter and BASEURL variables which we will be using erstwhile.
  2. steem.api.setOptions({ url: 'https://api.steemit.com' }); sets the url of the endpoint to https://api.steemit.com. Recently there were some changes made to the endpoints and a couple of witness servers were not working. In case you are getting any errors google for other endpoints and update them accordingly.
  3. Minitor the blockchain with steem.api.streamTransactions function, decorate/process them using the function getMessagefromTransaction(txType, txData)
  4. Using jQuery prepend the output to the div we created earlier in HTML with id "steem-data-wrapper". We will be using jQuery for prepending this value.

The processing function

The processing function uses a switch case to identify the different types of transactions and returns a relevant activity message.

  function getMessagefromTransaction(txType, txData) {
    //console.log(txType, txData) ;
    //console.log(txType, JSON.stringify(txData)) ;
    var custom_json;
    switch (txType) {
      case 'vote':
        return steemAuthorLink(txData.voter) + ' upvoted ' + steemAuthorLink(txData.author) + "'s post " + getLink(txData.title, steemBlogFullurl(txData.author, txData.permlink));
        // statements_1
        break;
      case 'comment':
         if (txData.parent_author == ''){
           return steemAuthorLink(txData.author) + ' created a post ' + getLink(txData.title, steemBlogFullurl(txData.author, txData.permlink));
         }else {
            return steemAuthorLink(txData.author) + ' posted a comment' + ' on '+ getLink(txData.permlink, steemBlogFullurl(txData.author, txData.permlink));
         }
        break;
      case 'transfer':
        return steemAuthorLink(txData.from) + ' transferred ' + txData.amount + ' to '+ steemAuthorLink(txData.to) + ' with the memo "' + txData.memo + '"';
        break;
      case 'claim_reward_balance':
        return steemAuthorLink(txData.account) + ' claimed his remaining rewards balance of ' + txData.reward_steem + ", "+  txData.reward_sbd + " and " + txData.reward_vests;
        console.log(txType, txData) ;
      break;
      case 'custom_json':
          if (txData.id == 'follow') {
            custom_json = JSON.parse(txData.json);
            return steemAuthorLink(custom_json[1].follower) + ' followed ' + steemAuthorLink(custom_json[1].following);
          }
      default:
        return txType + ' ' + JSON.stringify(txData).substring(0,300) + ((txData.length > 300) ? "....." : "");
        break;
    }
  }

Following Helper functions are used to generate links to the authors and blogs.

  function steemBlogFullurl(author, permlink) {
      return BASEURL + '@' + author + '/' + permlink;
  }
  function steemBlogFullurl(author, permlink) {
      return BASEURL + '@' + author + '/' + permlink;
  }
  function steemAuthorFullurl(author) {
      return BASEURL + '@' + author;
  }
  function steemAuthorLink(author) {
    return getLink('@' + author, steemAuthorFullurl(author));
  }
  function getLink(linkText, targetLink) {
    if (typeof linkText == "undefined" || linkText == ''){
      linkText = targetLink;
    }else if (typeof targetLink === "undefined") {
      targetLink = linkText;
    }
    return `<a href = ${targetLink} target="_blank">${linkText}</a>`;
  }

Final notes.

You can checkout the final code and the demo to see what you have created with the help of this tutorial.

 

Originally published on https://steemit.com/utopian-io/@gokulnk/build-matrix-like-steem-stream-…

AngularJS Series: An introduction to Scope

This is the Sixth post in my series on the AngularJS; have a look on my initial posts covering ‘An intro to AngularJS’, ‘Data-binding methods’, ‘Modules & controllers', 'Filters' and ‘Custom services’. 

Before jumping to another component of AngularJS - Scope - let’s make sure you all have seen the term $scope under controller function(). Scope is used to access variable and methods in Angular. 

As the name suggests, $scope means ‘within the range’. In Angular, $scope is a reserved word. As per the name $scope does the same by availing variable/functions () within the range. So the same variable could be rendered in the view. 
 
Technically:  $scope is service for AngularJS. It is an object that refers to a model. It acts as a mediator between the View & the Controller. It allows accessing properties and variable Within the scope. Scope looks to expression in your view and performs the event.

Sample code:

The below source code allows you to print the data directly from the Scope. As you can see our custom app has myCtrl controller and data is bind to the scope using $scope.name & $scope.job. The same variable can be pulled up in view while rendering the data. We have used {{name}} &  {{job}} in our view.
 

Response Result:

Scope output

Another way to create a controller 

You might have come across a situation where you need to develop a huge application of not just 50-100 lines of code but 10X larger than that. In this scenario, it's very difficult to manage each and every controller and get a minified version of JS script. When we talk about the minified version that means it will remove unnecessary blank space, comment and try to look for parameter and transform it to very simple name.  

While compiling new variable ‘b’ will be replaced with $scope.

Sample code :  

Every App has a local & global scope (root scope), where $rootScope never bound with any controller. In other words, $rootScope is a parent controller where are $scope_1 ,$scope_2…..$scope_n are the child of parent controller(---------    ) and can be accessible from anywhere in the application. Here variable has the same name and calls out within the scope and outside of the scope. In this scenario, variable within the local scope gets executed before root scope.

Let me share one small example:

Code Simplification: 

In above codebase, a module has two controllers including run().
run() is one of the phases of code execution order. Only constant and an instance can be taken up and called right after config(). In other words, you can use run() to boost the application.

Back to code: we have two controller myCtrl & yourCtrl. These controllers are called within local scope whereas $rootScope have an object in global scope and rendered the same in the view.

To access the $rootScope property or methods within the controller,  you need to mention $root. Method_name or $root.property_name


 
Global scope within local scope : You are logged in as: {{ $root.name}} & your profession as {{ $root.job}}

In case you need $rootScope inside the local scope of your controller then you need to pass $rootScope as Dependency injection in your local scope of the controller.

In below source code $rootScope.job will take up the value from the global controller and assign back to myCtrl. Using this technique, global data can be passed through multiple controller and local data within the same controller.

 app.controller('myCtrl', function($scope, $rootScope) {
                              $scope.name = "Jaywant Topno";
                              $scope.job = $rootScope.job;
                   });

Sample response:

Scope output with controller

This is what Scope in AngularJS all about. The goal of our series of tutorial on AngularJS is to bring you valuable information to help you gro tow enhance your technical knowledge. We hope you enjoy this post!

Git Source code: https://github.com/xaiwant/AngularJS-Scope

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch