Categories
Dev Bootcamp

What is a SQL Injection?

What is a SQL injection?

In general terms, code injection is the “exploitation of a computer bug that is caused by processing invalid data.” An attacker can use this exploit to introduce (or “inject”) code into a program and change the intended action of the program, which, as you can imagine, can be very dangerous.

SQL is a language that is used to communicate with databases. When a web page uses SQL to display data from a database, it is common to allow users to input their own search values. When you do a search on a website, it will usually run a SQL query. When you click on an ecommerce shopping refinement/filter, it will run a SQL query. When you log in with your username and password, it will run a SQL query; etc., etc. In specific terms, SQL injection is a technique where an attacker injects SQL commands into an SQL statement where it is unintended (i.e. a web page input field).

How is SQL injection performed?

Here is the most common and easiest example to use to understand the concept of SQL injection.

Let’s say you have a database that stores all of your clients’ information. Your database has a Users table with a Username column and a Password column. On your web page, your client can view their profile and stored information by typing in their username and password into the two fields to log in.

Example

Username: Password:

A simple underlying SQL statement that is used to validate the username and password and retrieve user information would be:

SELECT ID, DoB, SSN, CreditCardNum
FROM Users
WHERE Username = $username
AND Password = $password

The variable $username contains whatever you input into the username field and the variable $password contains whatever you input into the password field.

Intended Use

So if I type in tmai into the username field and h@$hy into the password field (note: not real) and submit it, the following SQL statement will run.

Username: Password:

SELECT ID, DoB, SSN, CreditCardNum
FROM Users
WHERE Username = 'tmai'
AND Password = 'h@$hy'

If Username = 'tmai and Password = 'h@shy' tests true, then the SQL statement will retrieve my ID, date of birth, social security number, and credit card number from the Users table. This is pretty sensitive information.

Malicious Use

Now, an attacker can inject SQL by doing the following:

Username: Password:

Which in turn, runs the following SQL statement:

SELECT ID, DoB, SSN, CreditCardNum
FROM Users
WHERE Username = 'tmai'
AND Password = 'randomtext' OR '1' = '1'

Notice the difference in the last line of the SQL statement? From the query above, '1' + '1' will ALWAYS be true. That means that the expression Password = 'randomtext OR '1' = '1' will be true. The attacker just successfully tricked the web page into showing all of the sensitive information that belongs to me without actually knowing my password.

The attacker can also inject SQL commands like DELETE to erase specific data and DROP to erase entire tables and even databases!

How can I prevent SQL injections?

There are several methods to safeguard your webpages from possible SQL injections. One method is to use data validations for your input forms against specific lengths, data types, or syntax. This may not be the best method, since it may be too limiting on what your users are allowed to type into these fields, especially if these restrictions include commonly used words. Another method to protect your database is to limit the webpage’s privileges to the database.

The better method, though, is to use SQL parameters. The SQL engine will check each parameter individually against its intended column instead of treating it as part of the entire SQL statement to be executed. To learn more about this, w3schools.com provides a lot of good examples on how to “parameterize” your SQL queries.

Now that you understand what SQL injection is and how it can be performed, make sure to take the necessary steps to protect your data.

Further Reading:

This blog has been initially published on tonymai.github.io.

Categories
Dev Bootcamp

What Are Your Values? Use It To Affirm Your Self-Worth

There were so many moments in my life where I was happy and proud: winning 1st place in a national Macy’s marketing challenge, partying and making mistakes, making life-long friends and family, graduating from college, receiving a high GMAT score, running 10-miles within one month of training, completing the Spartan Race Beast, traveling around the world, etc.

While looking at the list of values provided from my latest Dev Bootcamp challenge, when I think of the times in my life where I’ve been the happiest, the proudest, or the most satisfied, these are the ones that come to my mind:

  • Accomplishment
  • Achievement
  • Ambition
  • Challenge
  • Competition
  • Excitement
  • Friendships
  • Growth
  • Inspiration
  • Knowledge
  • Leadership
  • Meaningful work
  • Personal develpmnt
  • Physical challenge
  • Pleasure
  • Will-power

It’s quite a long list, but each one of these values is very meaningful to me.

If I had to rank them by whether or not I try to live up to these values in general, here is what it would be:

values

As you can see, I generally try to live up to all of the values that I find important to me.

One very important value to me from this already trimmed-down list is growth. For me personally, all of the values on the list are secondary values that support the primary value: growth. Everything is ever-changing and you need to continuously learn and grow. Friendship, ambition, inspiration, knowledge, will-power, etc., are all there to support my growth.

The last time someone asked for my advice, it was from a soon-to-be graduate (at the time) in regards to post-college life, jobs, careers, and the future. We discussed various topics, from networking to applying what you learn (to trying many things and doing what you love). Most, if not all, of the topics that I advised on relates to a lot of the values that I find important to myself.

So why am I thinking about my values? Why is it important?

Because thinking about my values helps me remind myself of everything that I hold important to me. They can also help me mediate stereotype threat if I recognize that I feel it. When I think about my core values and how they help create my happiest, proudest, and or more satisfied moments, I realize what is important; and performance based on my gender, race, or ethnicity is not one of them. My values and actions are what create my self-worth; not stereotypes. Studies have also shown that students who have been led to self-affirm are less likely to be susceptible to stereotype threats and perform better than those who have not been [source].

Another way that can help when you feel that your performance is being hindered because of stereotype threat is to look up to a role model with the same social identity. If they can achieve success, then so can you. Furthermore, intelligence is not fixed. It grows as you learn, which goes back to my highly-regarded value. Challenges, problems, and difficulties will only help you grow, learn, increase your intelligence, and eventually overcome those challenges.

This blog has been initially published on tonymai.github.io.

Categories
Dev Bootcamp

From Ruby Hashes to JavaScript Object Literals

From the perspective of someone who has a primer on Ruby and jumping onto JavaScript, I noticed something used very often in Ruby that is missing from JavaScript: Ruby Hashes. How can such a powerful data type not exist in other object-oriented languages? If you are also completely new to JavaScript and have the same question, fear not! There is something in JavaScript we can use to achieve the same features provided by Ruby Hashes: JavaScript Object Literals.

MDN defines an object literal as “a list of zero or more pairs of property names and associated values of an object.” As you can see from the definition, this is very similar to Ruby Hash‘s pairs of keys and associated values.

Here is a side-by-side comparison of creating, reading, changing, adding, and deleting a new JavaScript object literal versus a new Ruby hash literal:

JavaScript Object Literal:

//creating new JS object literal
var capitals = { spain: "Madrid",
  france: "Paris",
  italy: "Rome",
  hungary: "Budapest",
  germany: "Berlin"
};

//accessing JavaScript object value
capitals["france"]; //returns "Paris"
capitals["belgium"]; //returns undefined

//changing values
capitals["france"] = "Nice";

//adding a new property/value pair
capitals["russia"] = "Moscow";

//deleting a property/value pair
delete capitals["italy"];

//final result
console.log(capitals);
/*
prints:
{ spain: 'Madrid',
  france: 'Nice',
  hungary: 'Budapest',
  germany: 'Berlin',
  russia: 'Moscow' }
*/
Ruby Hash Literal:

#creating new Ruby Hash literal
capitals = { spain: "Madrid",
  france: "Paris",
  italy: "Rome",
  hungary: "Budapest",
  germany: "Berlin"
}

#accessing Ruby hash value
capitals[:france] #returns "Paris"
capitals[:belgium] # returns nil

#changing values
capitals[:france] = "Nice"

#adding a new key/value pair
capitals[:russia] = "Moscow"

#deleting a key/value pair
capitals.delete(:italy)

#final result
p capitals
=begin
prints:
{:spain=>"Madrid", :france=>"Nice", :hungary=>"Budapest", :germany=>"Berlin", :russia=>"Moscow"}
=end

See how similar they both are? Creating a JavaScript object literal is almost the same as creating a Ruby hash literal. It is important to note that while Ruby hash keys can be any data type (i.e. symbols, strings, integers, hashes, etc.), JavaScript object properties can only be variables. But they can point to any data type value, just like in Ruby hashes.

You can call a JavaScript object’s properties in a similar fashion as you would a Ruby hash‘s keys. Same with creating and deleting key/value and property/value pairs. Calling a non-existent key or property will return nil or undefined.

Note that while I used the bracket notation here to access and modify a JavaScript object’s properties, you can also use a dot notation. For a more in-depth explanation of the differences between the two types of notation, take a look at this medium article.

The next time you find yourself working with JavaScript and are looking to implement something similar to Ruby Hashes into your script, JavaScript object literals will fit the bill perfectly.

This blog has been initially published on tonymai.github.io.

Categories
Dev Bootcamp

Has Stereotype Threat Ever Affected You?

It’s Not You, It’s Stereotype Threat

Why do people from different social groups (age, gender, race, ethnicity, etc.) underperform when it comes to certain tasks? Is it because they’re not as intelligent? Maybe not. It probably has more to do with stereotype threat than the individual’s intelligence. Stereotype threat is the threat of being viewed through the lens of a negative stereotype or the fear of doing something that would confirm that stereotype. Simply being aware that you are being measured based on your social identity can subconsciously cause a self-handicap. The anxiety that comes with being judged stereotypically as a woman, Black, or even white male, can impede one’s performance.

stereotype-threatDr. Claude M. Steele, the social psychologist who developed the theory of stereotype threat, performed an experiment with two groups of Black and white college students, each taking a 30-minute test made up of questions from the GRE. “When one group was told that the test would measure their intellectual ability, Black students underperformed dramatically. But when another group was told the test could not measure intellectual ability, Blacks and whites performed at virtually the same level.” This is really interesting. He performed similar experiments with woman taking a math test that “measures” the differences between genders, white males taking a test that “measures” the differences between whites and Asians, etc., and the results were the same.

Another interesting result is that the more you care about what you are doing, the greater the effects of stereotype threats have on you. An intelligent Black college student who wants to do well may be more drastically affected by the awareness that he or she is being judged than someone who doesn’t care as much. It is because they have “more to lose”. The idea of being judged if you underperformed is upsetting. It takes cognitive resources away from you and undermines your performance.

asians-mathAs an Asian American, I grew up with to lot of stereotypes, but I’m not sure I have ever felt the effects of stereotype threats in my academic and professional career. I care about everything that I do, but I cannot recall a situation where stereotype affected my performance and what I do. Although it hasn’t happened to me, I can see it happening to others. Asian Americans are portrayed as a model minority, whom achieve a higher degree of socioeconomic success than the population’s average. Although this is a positive stereotype, the pressure of high expectations can still threaten one’s intellectual performance. I think positive stereotypes can cause a stereotype threat, too.

If you ever notice that others (and yourself) fall into a stereotype threat situation, you should help reaffirm that the tests and challenges that they go through are not there to measure their performance based on their social identity, whether it’s age, gender, race, ethnicity, etc. That’s not what challenges (in the classroom, workplace, life, etc.) are designed to test. They only provide a snapshot of your abilities at the moment. It doesn’t define who you are. You get better as you go. It may also help to look up to a role model or think about all of the challenges that you’ve overcame in the past. A stereotype is a generalization and oversimplification of an idea. They are not true for everyone.

You are your own individual.

 

Further Reading:

This blog has been initially published on tonymai.github.io.

Categories
Dev Bootcamp

Improperly-Used Variable Scopes are No Vacation

What Is Scope?

Scope refers to the reach or visibility of variables. In the object-oriented world, scope is very important. There are five types of variables/constant, each with varying levels of scope.

The different variable scopes are (in order of highest to lowest level of scope):

  • global variables
  • constants
  • class variables
  • instance variables
  • local variables

In objected-oriented design, you want classes and methods to have only single responsibilities. We don’t want to expose everything to everything. It would be a tangled mess to have all variables and methods available to all objects. This also creates a lot of dependencies. When you change one part of the code, you may need to change ten other parts of the code if they are all depending on the code that you are changing, creating a rippling effect. Using correct variable scopes to only expose what is needed helps reduce this problem.

Besides restricting access to other components of the code, scopes also keep the name space open. Since the variable is limited to its scope and is non-existent outside of it, you don’t have to worry about creating a variable with the same name and accidentally overwriting the previous assignment.

Let’s talk about each variable scope in more detail

Global Variables

Global variables have a global scope. They are available anywhere in the program. It is defined and called with a $ in front of the name (i.e. $global_variable = "I am a global variable").

Try not to use global variables unless it is absolutely necessary. There is almost always a way to substitute using global variables with something else. It is used often in functional programming, but is counter-intuitive to object-oriented programming (OOP) because it is doing exactly what OOP is designed to get rid of. Relying on global variables causes the program to become less flexible and harder to make changes to in the future. In OOP, each object should only expose what is needed; nothing more and nothing less (only expose what it does, not how it does it).

Constants

Constants also have a global scope. They start with a capital letter. The Ruby convention is to write it with in all caps and underscore (i.e. CONSTANT = "I am a constant"). If they are called from self, you only need to write the name of the constant, like local variables and methods. If you are calling from outside of self, you can still access it if you know the path of the block that defined the constant and :: (i.e. Math::PI).

Constants are not meant to be changed, but Ruby will allow it. If you choose to change a constant, Ruby will give you a warning and then make the change right afterwards.

Local Variables

Let’s jump to local variables before we talk about class and instance variables. If you’ve played with Ruby, then you’re probably already familiar with it. Local variables have a local scope and they start with a lowercase letter (i.e. local_variable = "I am a local variable"). Local variables are the most often used variables and are limited to the specific block it’s in and the blocks inside that block. They can’t be access from anywhere outside of the block.

For example:

class Destination
  def dest_1
    x = "Barcelona"
    puts x
  end
  def dest_2
    puts x
  end
end

trip = Destination.new 
trip.dest_1 # => "Barcelona"
trip.dest_2 # => undefined local variable or method `x' for #<Destination:0x007fe284058ae8> (NameError)

Or:

trip = ["Barcelona","Rome","Amsterdam"]
trip.each { |city| x = city; print x } # => BarcelonaRomeAmsterdam
print x # => undefined local variable or method `x' for main:Object (NameError)

As you can see, when the local variable is called outside of its block (in the first example, the Destination#dest_1 method block, and in the second example, the .each iterator block), it will create an error. Since the variable is out of scope, it does not exist in the block from which it is called upon.

Now, lets look at this example:

trip = ["Barcelona","Rome","Amsterdam"]
x = []
trip.each { |city| x = city; print x } # => "BarcelonaRomeAmsterdam"
p x # => "Amsterdam"

Something interested happens here. Notice how the last line now prints "Amsterdam", even though that was assigned inside the .each iterator block. Since x was first defined outside of the .each iterator block, the scope of the variable has changed. Remember what I said earlier: the scope of a local variable is limited to its block and the blocks within that block.

Instance Variables

Instance variables are only accessible to each specific instance. They begin with a @ symbol in front of the name. They are written inside instance methods and can be shared by all instance methods in that class. Since the scope of instance variables are restricted to each instance, different instances can have different values assigned to these variables.

Take this, for example:

class Destination
  def initialize(city)
    @city = city
  end
  def print_city
    puts @city
  end
end

trip_1 = Destination.new("Barcelona") 
trip_2 = Destination.new("Rome")
trip_1.print_city # => "Barcelona"
trip_2.print_city # => "Rome"

There are two things to note here. First, notice how @city is assigned in the Destination#initialize method and the assignment is still available in a different method, Destination#print_city (as evidenced by what the last 2 lines printed). The second thing to note is that @city for trip_1 is different from the @city for trip_2. Instance variables are the second most used variables in Ruby.

Class Variables

Class variables are accessible by the class and all instances of that class, so they have a wider scope than instance variables, but not as much as global variables. These variables have a @@ symbol in front of its name. They are often used if the class or any instance of the class will need to use it.

For example:

class Destination
  @@total_avail_cities = 0
  def initialize(city)
    @city = city
    @@total_avail_cities += 1
  end
  def print_total
    puts @@total_avail_cities
  end
end

trip_1 = Destination.new("Barcelona")
trip_1.print_total # => 1

trip_2 = Destination.new("Rome")
trip_2.print_total # => 2

Every time a new destination is initialized, it adds a count to @@total_avail_cities. Notice that even though trip_2 is a separate instance from trip_1, it still print 2.

Class variables are also avoided unless it is necessary. Similarly to global variables, not realizing its scope can be detrimental to your problem.

Here is an example:

class Destination
  def initialize(city)
    @@city = city
  end
  def print_city
    puts @@city
  end
end

trip_1 = Destination.new("Barcelona")
trip_2 = Destination.new("Rome")
trip_1.print_city # => "Rome"
trip_2.print_city# => "Rome"

Notice how both calls to print @@city returned "Rome". That is because the second instance changed the value of @@city when it was initialized, which carries over to all instances in that class. Be careful when using class variables and only use them when absolutely necessary.

Summary

Ruby has different types of variables that have varying levels of scope. The bigger the scope, the more careful you should be when using it. In object-oriented design, you only want what is absolutely needed to be accessible by others to make your program work, so don’t expose anything in an object that isn’t needed by others. Keep the scope in mind and choose which variables to use accordingly.

This blog has been initially published on tonymai.github.io.