How to use CareerWave to upload image or Multiple images for single Record.


I follow Careerwave main Article to get my task Done.

there are many things to do but here is short way to do the same-

I am trying to upload multiple images in Product.

Add Gem-  gem 'carrierwave', '~> 1.0'

2. Bundle install    bundle

3. Start off by generating an uploader:

rails generate uploader Avatar

4. this should give you a file in:

app/uploaders/avatar_uploader.rb
5. Add following configuration-

config/environment.rb

require ‘carrierwave/orm/activerecord’

6. Create migration to add new field in table (Product).

rails g migration add_avatar_to_products avatar:string

(Or)

rails g migration add_avatar_to_products avatars:json

Note- if you want single image to upload then use first command else second for multiple images-

rake db:migrate

I am considering second one because I need multiple images for each product and that i can done without using any other  separate table.

7. In model add-

class Product < ApplicationRecord
mount_uploaders :avatars, AvatarUploader
end

8. app/uploaders/avatar_uploader.rb should look like this-

class AvatarUploader < CarrierWave::Uploader::Base
storage :file

def store_dir
‘public/my/upload/directory’
end

# Provide a default URL as a default if there hasn’t been a file uploaded:
def default_url(*args)
# For Rails 3.1+ asset pipeline compatibility:
# ActionController::Base.helpers.asset_path(“fallback/” + [version_name, “default.png”].compact.join(‘_’))
“/images/fallback/” + [version_name, “default.png”].compact.join(‘_’)
end

# def scale(width, height)
# # do something
# end

# Create different versions of your uploaded files:
# version :thumb do
# process resize_to_fit: [50, 50]
# end

# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_whitelist
%w(jpg jpeg gif png)
end
def content_type_whitelist
/image\//
end

# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# “something.jpg” if original_filename
# end

end

9. Add in strong parameter as-

{avatars: []}

so it should look like this-

class ProductsController < InheritedResources::Base

Private

def product_params

params.require(:product).permit(:category_id, :brand_name, :user_id, :fabric, :color, :size, :price, {avatars: [})

end

10. On form add following-

<%= form.file_field :avatars, multiple: true %>

That worked for me as expected!
Advertisements

How to print ERD of existing Database (Schema) in rails


Many time we require to print Database ERD. In rails we have  Rails-Erd gem to make this task done.

rails-erd gem which will allow us to quickly generate ERD diagrams. After that, we’ll set up a rake task so that everyone on the project uses the same command to generate the diagrams.

First, we’ll simply add rails-erd to Gemfile:

group :development do
  gem 'rails-erd'
end

Now install bundle to get the library of the same.

$ bundle
You will get notification to install graphviz on the bottom of command and ask you to install it.

We require to install graphviz to get print ERD in PDF.
Open terminal and type below command.
$ sudo apt-get install graphviz
Once install all above libraries then we can print ERD by using following command.
$ erd
if above command does not worked we can try-
$ bundle exec erd.

Have nice day!

How to create API in rails 5 from Scratch using JWT Authenticate.


I was in the need to do the same, after wondering here and there I started and below are the steps-

This most and mandatory this is authentication of API, that we can do using JWT. Most of developer use Device to get authentication done for web site.

As we don’t need many thing if we are taking about API like(Send confirmation mail).

Let’s start Now-

We’ll begin by building a model for our app. The application will authenticate user, so let’s create a User model.

$ rails g model user email:string password_digest:string confirmation_token:string confirmed_at:datetime confirmation_sent_at:datetime

Above will generate a file in db/migrate with timestamp, like –

create_table :users do |t|
  t.string :email,              null: false
  t.string :password_digest,    null: false
  t.string   :confirmation_token
  t.datetime :confirmed_at
  t.datetime :confirmation_sent_at

  t.timestamps
end

Now we need to run migrate to get user table in database.

So run $ rails db:migrate 

We’re adding email and password_digest columns here, which are the basic columns required to register or authenticate a user. Of course, you can add more columns that makes sense, if you like. The confirmation_tokenconfirmed_at, and confirmation_sent_at columns are required for user confirmation. You can skip this if you don’t wish to confirm the emails.

Validations

Let’s add our validations to models/user.rb:

validates_presence_of :email
validates_uniqueness_of :email, case_sensitive: false
validates_format_of :email, with: /@/

We’re validating the uniqueness of email without case sensitivity and doing a simple format check of the email ensuring there is a @ in the email string. This might not be a solid validation, but there is no standard one and that’s why we verify the email upon registration.

 

Callbacks

We are going to make use of Rails’s hassecurepassword for handling the password hashing.

To start, add the gem bcrypt (it’s probably there, but commented out) to your Gemfile and run bundle install. Once the gem is installed, add the following line inside the User class in the file models/user.rb:

class User < ApplicationRecord
  has_secure_password
  ...

Let’s also add callbacks that we want to perform before user creation. First, we’d want to lowercase the email and strip any spaces. Second, we’d have to generate a confirmation token that will be sent in the email to the user.

Add these before callbacks to the models/user.rb file:

before_save :downcase_email
before_create :generate_confirmation_instructions

We downcase the email before saving it to the DB. The confirmation instructions should be generated only during the creation of the user record. Let’s add the methods:

def downcase_email
  self.email = self.email.delete(' ').downcase
end

def generate_confirmation_instructions
  self.confirmation_token = SecureRandom.hex(10)
  self.confirmation_sent_at = Time.now.utc
end

If you plan to skip the confirmation, you can omit the above method and the corresponding callback.

Registration

Create

We now have the model setup, so let’s add an endpoint for user creation. Create our users controller:

rails g controller users

Add the below line to config/routes.rb:

resources :users, only: :create

We now have generated our UsersController. Head over to the controller (app/controllers/users_controller.rb) and add the following lines:

def create
  user = User.new(user_params)

  if user.save
    render json: {status: 'User created successfully'}, status: :created
  else
    render json: { errors: user.errors.full_messages }, status: :bad_request
  end
end

private

def user_params
  params.require(:user).permit(:email, :password, :password_confirmation)
end

incase above do not work we can try with-


def user_params
  params.permit(:email, :password, :password_confirmation)
end

 

We now have an API endpoint to create a user! You can try it by starting the server and sending a POST request with the user details as JSON in the body. Here’s an example of what you could post to http://localhost:3000/users:

open postman and set credential as-

URL- http://localhost:3000/users

Method- POST

Body- 

email: demo@example.com
password: secure
password_confirmation: secure

You should receive the User created successfully message as the response. Subsequent requests with the same data should respond with error messages. That’s our validations in play. For those who are skipping the confirmation part, you can skip the following and head to the Login section.

Confirmation

One thing that is pending is the user confirmation. We are going to send an email confirmation to the user before creation and create an endpoint that validates the token to confirm the user.

To start, we have to send an email to the user when the record is successfully created. We wouldn’t be going through how to send emails since there are already good tutorials that cover how to do it. We should add the line to send email right after user.save in users_controller.

Just make sure that you include the user.confirmation_token in your email. Ideally, the URL should lead to an endpoint that fetches the token and posts it to our API. Let’s create that post API endpoint.

Adda route to our config/routes.rb file for the confirm endpoint:

resources :users, only: :create do
  collection do
    post 'confirm'
  end
end

Now, create the confirm action in UsersController:

def confirm
  token = params[:token].to_s

  user = User.find_by(confirmation_token: token)

  if user.present? && user.confirmation_token_valid?
    user.mark_as_confirmed!
    render json: {status: 'User confirmed successfully'}, status: :ok
  else
    render json: {status: 'Invalid token'}, status: :not_found
  end
end

Let’s see what we’re doing here. First, we are fetching the token from params, callingto_s to handle the case where the token is not sent in the request. Next, fetch the corresponding user based on the confirmation token.

If the user is present and the confirmation isn’t expired, call the model method mark_as_confirmed! and respond with a success message. We have to add the confirmation_token_valid? and mark_as_confirmed! methods to our User model:

def confirmation_token_valid?
  (self.confirmation_sent_at + 30.days) > Time.now.utc
end

def mark_as_confirmed!
  self.confirmation_token = nil
  self.confirmed_at = Time.now.utc
  save
end

The confirmation_token_valid? method checks if the confirmation was sent in the last 30 days and, thus, is not expired. You can change it to any value you wish.

mark_as_confirmed! saves the confirmed time and nullifies the confirmation token so that the same confirmation email can’t be used to confirm the user again.

We now have the endpoint to confirm a user. You can test it by sending a post request to the endpoint users/confirm?token=<CONFIRMATION_TOKEN> and check the confirmed_at and confirmation_token value for the user. You should get User confirmed successfully. Subsequent requests with the same token should return Invalid token.

open postman and set credential as-

URL- http://localhost:3000/users

Method- POST

Body

token: eec39106c725e1da6a57

We now have a working registration as part of our app. Let’s create the final piece: the login endpoint.

Login

For login, we are going to create an endpoint to log the user in by sending the credentials of the user and responding with a JWT token. We also will add a helper method that can be used to secure endpoints that we want to be exposed only to authenticated users.

Controller

Let’s add the login route to our config/routes.rb file under users resource:

resources :users, only: :create do
    collection do
      post 'confirm'
      post 'login'
    end
end

We have created a users/login route now. The controllers require some modification to pull in the json_web_token code and create the corresponding action in the UsersController.

In controllers/application_controller.rb, add the below line right after the class definition:

require 'json_web_token'

In controllers/users_controller.rb add the following snippet:

def login
  user = User.find_by(email: params[:email].to_s.downcase)

  if user && user.authenticate(params[:password])
      auth_token = JsonWebToken.encode({user_id: user.id})
      render json: {auth_token: auth_token}, status: :ok
  else
    render json: {error: 'Invalid username / password'}, status: :unauthorized
  end
end

Let’s go over this method step by step. First, we’re fetching the user from the email and, if present, call the authenticate method passing the password that is supplied. The authenticate method is provided by the has_secure_passwordhelper.

Once we verify the email and password, encode the user’s id into a JWT token via our encode method from JsonWebToken lib which we have yet to create. Then, return the token.

For those who are confirming emails, we have to disallow users who aren’t confirmed. Modify the controller action to include one more conditional:

...
if user && user.authenticate(params[:password])
  if user.confirmed_at?
    auth_token = JsonWebToken.encode({user_id: user.id})
    render json: {auth_token: auth_token}, status: :ok
  else
    render json: {error: 'Email not verified' }, status: :unauthorized
  end
else
...

Checking if the confirmed_at field is not empty does the job, meaning user has been confirmed before allowing them to login.

JWT Library

Now, let’s add the JWT library. Begin by adding the following gem to your Gemfileand do bundle install:

gem 'jwt'

Once done, create a file calledjson_web_token.rb under lib/ and add these lines:

require 'jwt'

class JsonWebToken
  # Encodes and signs JWT Payload with expiration
  def self.encode(payload)
    payload.reverse_merge!(meta)
    JWT.encode(payload, Rails.application.credentials.secret_key_base)
  end

  # Decodes the JWT with the signed secret
  def self.decode(token)
    JWT.decode(token, Rails.application.credentials.secret_key_base)
  end

  # Validates the payload hash for expiration and meta claims
  def self.valid_payload(payload)
    if expired(payload) || payload['iss'] != meta[:iss] || payload['aud'] != meta[:aud]
      return false
    else
      return true
    end
  end

  # Default options to be encoded in the token
  def self.meta
    {
      exp: 7.days.from_now.to_i,
      iss: 'issuer_name',
      aud: 'client',
    }
  end

  # Validates if the token is expired by exp parameter
  def self.expired(payload)
    Time.at(payload['exp']) < Time.now
  end
end

Let’s go through the code. First, in the encode method, merge the payload which is the user id with meta information such as expiry, issuer, and audience. You can learn about these “meta” claims from the JWT tutorial linked at the beginning of this post. Once merged, encode the payload using the JWT.encode method along with the secret key from our server. It is important that this key is kept secure since this is the master key for all the tokens our app issues.

Then, the decode method, which uses the decode method from the jwt gem to (you guessed it) decode the payload using the secret key. We have a couple of other helper methods, one is valid_payload which validates if the payload has been tampered with, and the expired method which validates whether the token has expired. The default expiry is set in the meta method which is 7 days, but you are free to change it as per your requirement.

Now we have a functioning login endpoint that we can use to login the user. Try calling the endpoint users/login with the below formatted data in the request body:

 

open postman and set credential as-

URL- http://localhost:3000/users

Method- POST

Body

email: demo@example.com

password: secure

You should see a response similar to this,

{
  "auth_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE0NzUzMTM5OTQsImlzcyI6Imlzc3Vlcl9uYW1lIiwiYXVkIjoiY2xpZW50In0.5P3qJKelCdbTixnLyIrsLKSVnRLCv2lvHFpXqVKdPOs"
}

There it is. Our authentication token for the user. We can now use this token to validate each request for the user.

Authentication Helper

Alright, we are going to create a helper method that gets the token from the header, validates the payload, and fetches the corresponding user from the DB. Open up /app/controllers/application_controller.rb and add the following:

protected
# Validates the token and user and sets the @current_user scope
def authenticate_request!
  if !payload || !JsonWebToken.valid_payload(payload.first)
    return invalid_authentication
  end

  load_current_user!
  invalid_authentication unless @current_user
end

# Returns 401 response. To handle malformed / invalid requests.
def invalid_authentication
  render json: {error: 'Invalid Request'}, status: :unauthorized
end

private
# Deconstructs the Authorization header and decodes the JWT token.
def payload
  auth_header = request.headers['Authorization']
  token = auth_header.split(' ').last
  JsonWebToken.decode(token)
rescue
  nil
end

# Sets the @current_user with the user_id from payload
def load_current_user!
  @current_user = User.find_by(id: payload[0]['user_id'])
end

Here, authenticate_request! is the helper method that we are going to use to authenticate controller actions. It fetches the payload from the Authorizationheader of the request, then validates the payload using the valid_payloadmethod, which we’ve seen before. Once confirmed valid, it fetches the user using the user_id in the payload, loading the user record into the scope.

We can now add the authenticate_request method as a before_filter to any controller action that we want to be authenticated for the user as-

You should see a response similar to this,


class VehiclesController < ApplicationController

before_action :set_vehicle, only: [:show, :update, :destroy]
  before_action :authenticate_request!
  # GET /vehicles
  def index
    @vehicles = Vehicle.all
    json_response(@vehicles)
  end
end

This blog source is available on sitePoint.

Make sure route have-

resources :vehicles to get response and click postman as-

URL- localhost:3000/vehicles

Method- GET

Header-

Authorization : eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MzMxMjQyNjUsImlzcyI6Imlzc3Vlcl9uYW1lIiwiYXVkIjoiY2x

pZW50IiwidXNlcl9pZCI6MX0.ibhJ_rsQ0xgLbey4TyGkrjLTqFjwEPJOzDZ9OfzKNp0

Response-


[
{
"id": 1,
"title": "Hello Car",
"color": "gray",
"make": "Toyota",
"model": null,
"plate_no": "UP-45 5126",
"engin_type": "Petrol",
"yop": "2016-07-23",
"user_id": null,
"created_at": "2018-07-24T10:24:35.517Z",
"updated_at": "2018-07-24T10:24:35.517Z"
},
{
"id": 2,
"title": "Ferri",
"color": "white",
"make": "Tata",
"model": null,
"plate_no": "DL-45 2321",
"engin_type": "Disel",
"yop": "2016-03-27",
"user_id": 2,
"created_at": "2018-07-24T13:10:05.424Z",
"updated_at": "2018-07-24T13:10:05.424Z"
},
{
"id": 3,
"title": "axcent",
"color": "white",
"make": "Hundai",
"model": null,
"plate_no": "UK-45 5545",
"engin_type": "Diesel / CNG",
"yop": "2013-03-13",
"user_id": 1,
"created_at": "2018-07-24T13:29:29.169Z",
"updated_at": "2018-07-24T13:29:29.169Z"
}
]

Ruby on Rails website Security Basic to be take care of…


Source o this article is available here.

Recently I have been working on my first Rails application, even though I have been working with Ruby for a number of years, this is the first time I’ve ever developed an application using the Rails framework. By trade, I’m a Security Tester, however, I do like to work on software projects in order to keep my skills sharp and practice what I preach.

Rails has some security features built in and enabled by default, however, I also recommend installing some additional Gems which cover security features Rails lacks by default. This article explains what are the basic Ruby on Rails built in security features and which are the gems I recommend intsalling.

Ruby on Rails Built in Security Features

I’m a great believer in secure by default and making security easy for developers. Some may argue that by making security easy, it will make developers pay less attention to security and possibly lead them to making more security mistakes. Kind of like a horse with blinkers on. In reality I think it is probably a balance, don’t make security invisible to the developer but instead make it just easy enough for them to implement correctly.

So be warned! Don’t just rely on Rail’s built in security features thinking that they offer a 100% effective way at mitigating the vulnerabilities they were designed to prevent against. Instead, learn how to use them correctly and know their limitations.

Preventing Cross-Site Scripting (XSS)

To help prevent Cross-Site Scripting (XSS) vulnerabilities we sanitise input and encode output using the correct encoding for the output context.

Sanitising Input

Rails makes sanitising input easy with its Model View Controller (MVC) design. Any data stored or retrieved from a database should pass through a Model, so this is a great place to sanitise our stored data. Using Active Record Validations within our models we can ensure that data is present and/or in a specific format.

You can also sanitise input/output within your View using the sanitize method. The sanitize method ‘will html encode all tags and strip all attributes that aren’t specifically allowed’. Let’s pass it a common XSS payload and see how it reacts:

<%= sanitize '<img src=x onerror=prompt(1)>' %>

The above will output:

<img src=“x”>

As we can see the sanitize method has allowed our img tag with the src attribute, but it has  removed the onerror event attribute. By default, if we don’t whitelist which tags/attributes we want, Rails will make that decision for us on what it believes is ‘safe’.

If we whitelist the src and onerror attributes, our XSS payload is executed:

<%= sanitize '<img src=x onerror=prompt(1)>', attributes: %w(src onerror) %>

The above will output:

<img src="x" onerror="prompt(1)">

Encoding Output

In modern versions of Rails, strings output in the View are automatically encoded. However, there may be occasions when you want to encode HTML output by yourself. The main output encoding method in rails is called html_escape, you can also use h() as an alias. The html_escape method ‘escapes html tag characters’.

Let’s pass it a common XSS payload and see how it reacts:

<%= html_escape '<img src=x onerror=prompt(1)>' %>

The above will output:

&lt;img src=x onerror=prompt(1)&gt;

As we can see the html_escape method has converted the < and > characters into html entities, ensuring the browser does not interpret them as markup.

This is the same output as we would see if we simply passed a string, thanks to Rails’s default encoding:

<%= "<img src=x onerror=prompt(1)>" %>

The above will output:

&lt;img src=x onerror=prompt(1)&gt;

But don’t forget what we said earlier! Just because modern versions of Rails encode strings in Views by default, does not mean that XSS can not happen. One example is within the href value of a link (using the link_to method).

Preventing Cross-Site Request Forgery (CSRF)

Modern versions of Rails protect against CSRF attacks by default by including a token named authenticity_token within HTML responses. This token is also stored within the user’s session cookie – when a request is received by Rails it checks one against the other. If they do not match, an error is raised.

It is important to note that Rails’s CSRF protection does not apply to GET requests. GET requests should not be used to change the application’s state anyway and should only be used to request resources.

Although enabled by default, you can double check that it’s enabled by seeing if the protect_from_forgery method is within the main ApplicationController.

Preventing SQL Injection

Rails uses an Object Relational Mapping (ORM) framework called ActiveRecord to abstract interactions with a database. ActiveRecord, in most cases, protects against SQL Injection by default, however, there are ways in which it can be used insecurely which can lead to SQL Injection.

Using ActiveRecord we can select the user with the supplied id and retrieve that user’s username:

User.find(params[:id]).username

The above will return the username of the user whose user id matches the one supplied via the params hash. Let’s take a look at the SQL query generated by the code above on the backend:

SELECT  "users".* FROM "users"  WHERE "users"."id" = ? LIMIT 1  [["id", 1]]

As we can see from the SQL query above, when using the find method on the User object ActiveRecord is binding id to the SQL statement. Protecting us from SQL Injection.
What if we wanted to select a user which matched a username and password, commonly seen in authentication forms. You might see something like this:

User.where("username = '#{username}' AND encrypted_password = '#{password}'").first

If we supply a username with the value ‘) OR 1– the corresponding SQL query on the backend becomes:

SELECT  "users".* FROM "users"  WHERE (username = '') OR 1--' AND encrypted_password = 'a')  ORDER BY "users"."id" ASC LIMIT 1

By injecting our specially crafted SQL, what we have done is told the database to return all rows from the users table where the username is null or true. This makes the SQL statement return true along with all of the data in the users table.

For some great examples of how not to use ActiveRecord, here’s a great resource which I suggest you check regularly to ensure you don’t have any of the examples within your code – http://rails-sqli.org/

Ruby on Rails Security Gems

As we have seen, Rails offers many built in security features to help protect our applications, data and users from web based attacks. But we also saw that these have their limitations. For security features that Rails does not offer by default there are always Gems, lots and lots of Gems. Here are some of my favourite.

devise

Devise is a popular authentication and authorisation Gem for Rails. It offers secure password storage using bcrypt to hash salted passwords. User lockouts, user registration, forgot password functionality and more.

Although Devise’s own README states “If you are building your first Rails application, we recommend you to not use Devise”, I would ignore this statement. If you’re security aware and have built applications in other frameworks before, I don’t see any issue with using Devise for your first Rails application.

URL: https://github.com/plataformatec/devise

brakeman

Brakeman is a Static Code Analysis tool for Rails applications. It searches your application’s source code for potential vulnerabilities. Although it does report the occasional False Positive, personally, I think this is a great Gem and one I would definitely recommend running against your application before going into production. Even better, run it after every commit.

URL: https://github.com/presidentbeef/brakeman

secure_headers

Developed by Twitter, SecureHeaders is a Gem that implements security related HTTP headers into your application’s HTTP responses. Headers such as Content Security Policy to help protect against Cross-Site Scripting (XSS) attacks, HTTP Strict Transport Security (HSTS) to ensure your site is only accessible over secure HTTPS, X-Frame-Options and others.

URL: https://github.com/twitter/secureheaders

rack-attack

Developed by Kickstarter, Rack::Attack is a Gem for blocking & throttling abusive requests.   Personally, I use Rack::Attack to prevent forms being abused, for example, instead of implementing a CAPTCHA on a submission form, I use Rack::Attack to ensure it is not submitted too many times in a short space of time. This should prevent automated tools from abusing the form submission. It also supports whitelisting and blacklisting of requests.

URL: https://github.com/kickstarter/rack-attack

codesake-dawn

Codesake::Dawn is similar to brakeman in that it scans your source code for potential vulnerabilities. However, Codesake::Dawn also has a database of known vulnerabilities which it uses to scan your Ruby, Rails and Gems for known issues.

URL: https://github.com/codesake/codesake-dawn

Ruby on Rails Code Quality Gems

Sloppy and messy code leads to bugs and some bugs may have security implications. Better quality code is more secure code. Let’s take a look at what Gems we can use to ensure our code is nice and clean.

rails_best_practices

The rails_best_practices Gem is a great Gem for ensuring your code is adhering to best practices. It will help you make your code more readable and eloquent by scanning through it and giving you suggestions on how to improve the syntax.

URL: https://github.com/railsbp/rails_best_practices

rubocop

Rubocop is not specific to Rails and can be used for any Ruby application. It uses the Ruby Style Guide as a reference to scan your code and ensure you adhere to it. Things like variable naming, method size, using outdated syntax, etc.

URL: https://github.com/bbatsov/rubocop

Have a nice day!!!

10 security tips to protect your website from hackers


Source of this article is as here.

 

You may not think your site has anything worth being hacked for, but websites are compromised all the time. The majority of website security breaches are not to steal your data or deface your website, but instead attempts to use your server as an email relay for spam, or to setup a temporary web server, normally to serve files of an illegal nature.

Hacking is regularly performed by automated scripts written to scour the Internet in an attempt to exploit known website security issues in software. Here are our top 10 tips to help keep you and your site safe online.

01. Keep software up to date

It may seem obvious, but ensuring you keep all software up to date is vital in keeping your site secure. This applies to both the server operating system and any software you may be running on your website such as a CMS or forum. When website security holes are found in software, hackers are quick to attempt to abuse them.

If you are using a managed hosting solution then you don’t need to worry so much about applying security updates for the operating system as the hosting company should take care of this.

If you are using third-party software on your website such as a CMS or forum, you should ensure you are quick to apply any security patches. Most vendors have a mailing list or RSS feed detailing any website security issues. WordPress, Umbraco and many other CMSes notify you of available system updates when you log in.

02. SQL injection

SQL injection attacks are when an attacker uses a web form field or URL parameter to gain access to or manipulate your database. When you use standard Transact SQL it is easy to unknowingly insert rogue code into your query that could be used to change tables, get information and delete data. You can easily prevent this by always using parameterised queries, most web languages have this feature and it is easy to implement.

Consider this query:

"SELECT * FROM table WHERE column = '" + parameter + "';"

If an attacker changed the URL parameter to pass in ‘ or ‘1’=’1 this will cause the query to look like this:

"SELECT * FROM table WHERE column = '' OR '1'='1';"

Since ‘1’ is equal to ‘1’ this will allow the attacker to add an additional query to the end of the SQL statement which will also be executed.

03. XSS

Cross site scripting is when an attacker tries to pass in JavaScript or other scripting code into a web form to attempt to run malicious code for visitors of your site. When creating a form always ensure you check the data being submitted and encode or strip out any HTML.

04. Error messages

Be careful with how much information you give away in your error messages. For example if you have a login form on your website you should think about the language you use to communicate failure when attempting logins. You should use generic messages like “Incorrect username or password” as not to specify when a user got half of the query right. If an attacker tries a brute force attack to get a username and password and the error message gives away when one of the fields are correct then the attacker knows he has one of the fields and can concentrate on the other field.

Keep your error messages vague

05. Server side validation/form validation

Validation should always be done both on the browser and server side. The browser can catch simple failures like mandatory fields that are empty and when you enter text into a numbers only field. These can however be bypassed, and you should make sure you check for these validation and deeper validation server side as failing to do so could lead to malicious code or scripting code being inserted into the database or could cause undesirable results in your website.

06. Passwords

Everyone knows they should use complex passwords, but that doesn’t mean they always do. It is crucial to use strong passwords to your server and website admin area, but equally also important to insist on good password practices for your users to protect the security of their accounts.

As much as users may not like it, enforcing password requirements such as a minimum of around eight characters, including an uppercase letter and number will help to protect their information in the long run.

Passwords should always be stored as encrypted values, preferably using a one way hashing algorithm such as SHA. Using this method means when you are authenticating users you are only ever comparing encrypted values. For extra website security it is a good idea to salt the passwords, using a new salt per password.

In the event of someone hacking in and stealing your passwords, using hashed passwords could help damage limitation, as decrypting them is not possible. The best someone can do is a dictionary attack or brute force attack, essentially guessing every combination until it finds a match. When using salted passwords the process of cracking a large number of passwords is even slower as every guess has to be hashed separately for every salt + password which is computationally very expensive.

Thankfully, many CMSes provide user management out of the box with a lot of these website security features built in, although some configuration or extra modules might be required to use salted passwords (pre Drupal 7) or to set the minimum password strength. If you are using .NET then it’s worth using membership providers as they are very configurable, provide inbuilt website security and include readymade controls for login and password reset.

07. File uploads

Allowing users to upload files to your website can be a big website security risk, even if it’s simply to change their avatar. The risk is that any file uploaded however innocent it may look, could contain a script that when executed on your server completely opens up your website.

If you have a file upload form then you need to treat all files with great suspicion. If you are allowing users to upload images, you cannot rely on the file extension or the mime type to verify that the file is an image as these can easily be faked. Even opening the file and reading the header, or using functions to check the image size are not full proof. Most images formats allow storing a comment section which could contain PHP code that could be executed by the server.

So what can you do to prevent this? Ultimately you want to stop users from being able to execute any file they upload. By default web servers won’t attempt to execute files with image extensions, but it isn’t recommended to rely solely on checking the file extension as a file with the name image.jpg.php has been known to get through.

Some options are to rename the file on upload to ensure the correct file extension, or to change the file permissions, for example, chmod 0666 so it can’t be executed. If using *nix you could create a .htaccess file (see below) that will only allow access to set files preventing the double extension attack mentioned earlier.

deny from all
    <Files ~ "^\w+\.(gif|jpe?g|png)$">
    order deny,allow
    allow from all
    </Files>

Ultimately, the recommended solution is to prevent direct access to uploaded files all together. This way, any files uploaded to your website are stored in a folder outside of the webroot or in the database as a blob. If your files are not directly accessible you will need to create a script to fetch the files from the private folder (or an HTTP handler in .NET) and deliver them to the browser. Image tags support an src attribute that is not a direct URL to an image, so your src attribute can point to your file delivery script providing you set the correct content type in the HTTP header. For example:

<img src="/imageDelivery.php?id=1234" />
     
<?php
      // imageDelivery.php
     
      // Fetch image filename from database based on $_GET["id"]
      ...
     
      // Deliver image to browser
       Header('Content-Type: image/gif');
      readfile('images/'.$fileName);  
     
?>

Most hosting providers deal with the server configuration for you, but if you are hosting your website on your own server then there are few things you will want to check.

Ensure you have a firewall setup, and are blocking all non essential ports. If possible setting up a DMZ (Demilitarised Zone) only allowing access to port 80 and 443 from the outside world. Although this might not be possible if you don’t have access to your server from an internal network as you would need to open up ports to allow uploading files and to remotely log in to your server over SSH or RDP.

If you are allowing files to be uploaded from the Internet only use secure transport methods to your server such as SFTP or SSH.

If possible have your database running on a different server to that of your web server. Doing this means the database server cannot be accessed directly from the outside world, only your web server can access it, minimising the risk of your data being exposed.

Finally, don’t forget about restricting physical access to your server.

09.SSL

SSL is a protocol used to provide security over the Internet. It is a good idea to use a security certificate whenever you are passing personal information between the website and web server or database. Attackers could sniff for this information and if the communication medium is not secure could capture it and use this information to gain access to user accounts and personal data.

Use an SSL certificate

10. Website security tools

Once you think you have done all you can then it’s time to test your website security. The most effective way of doing this is via the use of some website security tools, often referred to as penetration testing or pen testing for short.

There are many commercial and free products to assist you with this. They work on a similar basis to scripts hackers will use in that they test all know exploits and attempt to compromise your site using some of the previous mentioned methods such as SQL injection.

Some free tools that are worth looking at:

  • Netsparker (Free community edition and trial version available). Good for testing SQL injection and XSS
  • OpenVAS. Claims to be the most advanced open source security scanner. Good for testing known vulnerabilities, currently scans over 25,000. But it can be difficult to setup and requires a OpenVAS server to be installed which only runs on *nix. OpenVAS is fork of a Nessus before it became a closed-source commercial product.

The results from automated tests can be daunting, as they present a wealth of potential issues. The important thing is to focus on the critical issues first. Each issue reported normally comes with a good explanation of the potential vulnerability. You will probably find that some of the medium/low issues aren’t a concern for your site.

If you wish to take things a step further then there are some further steps you can take to manually try to compromise your site by altering POST/GET values. A debugging proxy can assist you here as it allows you to intercept the values of an HTTP request between your browser and the server. A popular freeware application called Fiddler is a good starting point.

So what should you be trying to alter on the request? If you have pages which should only be visible to a logged in user then I would try changing URL parameters such as user id, or cookie values in an attempt to view details of another user. Another area worth testing are forms, changing the POST values to attempt to submit code to perform XSS or to upload a server side script.

Use a debugging proxy to root out vulnerabilities

Hopefully these tips will help keep your site and information safe. Thankfully most CMSes have a lot of inbuilt website security features, but it is a still a good idea to have knowledge of the most common security exploits so you can ensure you are covered.

There are also some helpful modules available for CMSes to check your installation for common security flaws such as Security Review for Drupal and WP Security Scan for WordPress.

Remove many apks getting after Crosswalk integration in an Ionic app


here is the solution for the same, you can create new file as-

  1. Create a file named build-extras.gradle inside my /platform/android/ directory.
  2. put ext.cdvBuildMultipleApks=false inside it.
  3. ionic build android --release then and Voila, it worked.

(or)

the same can be done by adding one line in your existing file it will Take a minute and you can get the single build file by commenting out the

cdvBuildMultipleApks=true

line in the platforms/android/gradle.properties.

Cheers

         (Or)

to see single apk just use this command and To build separate APKs for x86 and arm7, use this command-

$ MUILD_MULTIPLE_APKS=true ionic run android

         (Or)

Removing Crosswalk
Crosswalk can removed two ways.

$ ionic browser revert android
# or
$ ionic browser remove crosswalk

you can also see here.

Have a nice day!!!

Sublime Text Keyboard Shortcut for easy use


Use these rapid keyboard shortcuts to control Linux, Mac OSX, and Windows versions of Sublime Text for all.

Key to the Keys

  • ⌘ : Command key
  • ⌃ : Control key
  • ⌫ : Delete key
  • ↓ : Down arrow key
  • ⌥ : Option or Alt key
  • ↩ : Return or Enter key
  • ⇧ : Shift key
  • ↑ : Up arrow key

: indicates that the step after the arrow should take place after the step before the arrow

General

Command Mac OSX Windows Linux
Open Cmd Prompt ⌘ + ⇧ + P Ctrl + ⇧ + P Ctrl + ⇧ + P
Toggle Side Bar ⌘ + K, ⌘ + B Ctrl + KB Ctrl + KB
Show Scope (Status Bar) ⌃ + ⇧ + P Ctrl + ⇧ + Alt + P Ctrl + ⇧ + Alt + P

Language

Command Mac OSX Windows Linux
Select File Language ⌘ + ⇧ + P [language] Ctrl + ⇧ + P [language] Ctrl + ⇧ + P [language]

Use the “Set Syntax: [language]” selection that is automatically populated in the command menu when you type the programming language.

Editing

Command Mac OSX Windows Linux
Delete Line ⌘ + X Ctrl + X Ctrl + X
Insert Line After ⌘ + ↩ Ctrl + ↩ Ctrl + ↩
Insert Line Before ⌘ + ⇧ + ↩ Ctrl + ⇧ + ↩ Ctrl + ⇧ + ↩
Move Line Up ⌘ + ⌃ + ↑ Ctrl + ⇧ + ↑ Ctrl + ⇧ + ↑
Move Line Down ⌘ + ⌃ + ↓ Ctrl + ⇧ + ↓ Ctrl + ⇧ + ↓
Select Line ⌘ + L Ctrl + L Ctrl + L
Select Word ⌘ + D Ctrl + D Ctrl + D
Multi-Select Editing ⌃ + ⌘ + G Alt + F3 Alt + F3
Jump to Closing Parenthesis ⌃ + M Ctrl + M Ctrl + M
Select Contents of Current Parentheses ⌃ + ⇧ + M Ctrl + ⇧ + M Ctrl + ⇧ + M
Delete from Cursor to End of Line ⌘ + K,⌘ + K Ctrl + KK Ctrl + KK
Delete from Cursor to Start of Line ⌘ + K + ⌫ Ctrl + K + ⌫ Ctrl + K + ⌫
Indent Current Line(s) ⌘ + ] Ctrl + ] Ctrl + ]
Unindent Current Line(s) ⌘ + [ Ctrl + [ Ctrl + [
Duplicate Line(s) ⌘ + ⇧ + D Ctrl + ⇧ + D Ctrl + ⇧ + D
Join Line Below Current Line ⌘ + J Ctrl + J Ctrl + J
Comment/Uncomment Current Line ⌘ + / Ctrl + / Ctrl + /
Block Comment Current Selection ⌘ + ⌥ + / Ctrl + ⇧ + / Ctrl + ⇧ + /
Redo/Repeat Last Keyboard Shortcut ⌘ + Y Ctrl + Y Ctrl + Y
Paste with Proper Indenting ⌘ + ⇧ + V Ctrl + ⇧ + V Ctrl + ⇧ + V
Select Next Autocomplete Suggestion ⌃ + Space Ctrl + Space Ctrl + Space
Soft Undo ⌃ + U Ctrl + U Ctrl + U
Column Selection Up ⌃ + ⇧ + Up Ctrl + Alt + Up Alt + ⇧ + Up
Column Selection Down ⌃ + ⇧ + Down Ctrl + Alt + Down Alt + ⇧ + Down

Transform

Command Mac OSX Windows Linux
To Uppercase ⌘ + K, ⌘ + U Ctrl + KU Ctrl + KU
To Lowercase ⌘ + K, ⌘ + L Ctrl + KL Ctrl + KL
Increase Font Size ⌘ + Ctrl + Ctrl +
Decrease Font Size ⌘ – Ctrl – Ctrl –

Find & Replace

Command Mac OSX Windows Linux
Find ⌘ + F Ctrl + F Ctrl + F
Replace ⌘ + ⌥ + F Ctrl + H Ctrl + H
Find in Files ⌘ + ⇧ + F Ctrl + ⇧ + F Ctrl + ⇧ + F
Use Selection for Find ⌘ + E Ctrl + E Ctrl + E
Use Selection for Replace ⇧ + ⌘ + E ⇧ + Ctrl + E ⇧ + Ctrl + E

Navigation

Command Mac OSX Windows Linux
Quick Open File (by Name) ⌘ + P Ctrl + P Ctrl + P
Go To Symbol ⌘ + R Ctrl + R Ctrl + R
Go To Line ⌃ + G Ctrl + G Ctrl + G

Code Folding

Command Mac OSX Windows Linux
Fold Selection ⌥ + ⌘ + [ ⇧ + Ctrl + [ ⇧ + Ctrl + [
Unfold Selection ⌥ + ⌘ + ] ⇧ + Ctrl + ] ⇧ + Ctrl + ]
Unfold All ⌘ + K, ⌘ + J Ctrl +KJ Ctrl + KJ

Bookmarks

Command Mac OSX Windows Linux
Toggle Bookmark ⌘ + F2 Ctrl + F2 Ctrl + F2
Next Bookmark F2 F2 F2
Previous Bookmark ⇧ + F2 ⇧ + F2 ⇧ + F2
Clear Bookmarks ⇧ + ⌘ + F2 ⇧ + Ctrl + F2 ⇧ + Ctrl + F2

It will help you to make task easy and faster if you use shortcut.

We can see more here as a source.

 

Thanks for reading,

HAve a nice Day !!!.

How to resolve Rails issue- An error occurred while installing mysql2 (0.4.4), and Bundler cannot continue. Make sure that `gem install mysql2 -v ‘0.4.4’` succeeds before bundling.


Hi all,

you may get this issue while working on Rails 4.0 and above version along with Ruby 2.0 and above.

this is very common issue if you are going ahead with up gradation of Rails environment.

Steps to be follow-

For Windows System-

  1. Download the the newest mysql-connector to c:\mysql-connector folder
  2. gem install mysql2 — ‘–with-mysql-include=”C:\mysql-connector\include” –with-mysql-lib=”C:\mysql-connector\lib”
  3.  

    Hopefully it will work for you.

For Ubuntu System-

  1. open terminal (Ctrl+alt+T)
  2. $ sudo apt-get install libmysqld-dev
  3. Run bundle from your project directory $ bundle

This will resolve the issue.

Have a nice Day !!!

What new in rails 5.0.0rc and its feature


Rails 5.0 and its importance-

Rails 5.0.0.rc1 was released May 6, 2016 and we can have a look on it by clicking this link.

From the start, Rails was praised for being the easiest way to get Ruby on the web.

Merging Rails API

Over the last few years, many thanks to Backbone.js and Angular.JS, the number of Single Page Applications (SPAs) are on the rise. The last few projects that I have built have been purely SPA and using Rails for these cases was an overkill.

NOTE: Before migrating to Rails 5 you need to make sure that your app works on Ruby 2.2.1.

Due to these enhancements, Ruby 2.2+ was a ripe candidate for Rails 5. Rails 5 will only work on Ruby 2.2.1 and above.

Tubolinks 3 allows you to retain most of your page and selectively update certain regions through partials. This is very similar to how SPA’s work, and you can choose to do all this from the server.

There were groans in the audience when DHH announced, again, his love for TurboLinks and their inclusion in Rails 5.

TurboLinks are a method for making your application feel a bit faster by using JavaScript to replace portions of content instead of reloading an entire page. But TurboLinks can also make an application a little heavy on client-side JavaScript, which can sometimes mean unresponsiveness or slowdowns.

If you are familiar with the functionality of TurboLinks in your application, do not fret! Things are not changing significantly. TurboLinks 3 will be an evolutionary step towards better speed and better rendering.

Note: The way React works is, it maintains a Virtual DOM where all the manipulations happen. It then diff’s the Virtual DOM and the actual DOM and makes only the required changes. It ensures that DOM is hit only when absolutely required and the changes are bare minimum.

Action Cable

The biggest news at RailsConf was the introduction of Action Cable. Action Cable is a feature used to extend Rails via WebSockets to add real-time message passing functionality.

Note: For the uninitiated, WebSockets is a W3C standard that opens up a duplex connection from your browser. Servers can talk (i.e., push updates) to clients as needed, and asynchronously update the client’s state without a full page reload. For instance, this is how Gmail loads new emails without reloading the entire page.

CoffeeScript

DHH has reaffirmed his love for CoffeeScript. Baked into Rails in version 3, CoffeeScript was made the default JavaScript option when using Rails. Some developers believed this was went too far.

One thing we can be sure of is: CoffeeScript is the default JavaScript flavour in Rails, and this won’t be going away anytime soon.

Ruby Version Support

Rails 5 will only support Ruby versions 2.2.1 and higher. As Ruby progresses as a language, backwards compatibility needs to be sacrificed for new features.

Some Niceties

1. Rake Inside Rails

For many a Rails noob, having to figure out when to use rake and when to use rails is a source of confusion. Now you don’t need to switch context between the rake and rails commands. You can run all Rake tasks with the rails keyword. For instance,

rake db:migrate

will now become:

rails db:migrate

This may not look like much on the surface, but this will make the lives of beginners much simpler. Rails 5 will also add a restart command that quickly restarts the application.

2. Active Record Changes

One change that almost went unnoticed was the update to belongs_to. When you create a Studentbelongs_to Class relation, it was possible to create a student without an associated Class relation. This lead to a lot of data inconsistencies. With Rails 5, he parent has become mandatory. If you try to insert an empty record here, Active Record will throw up.

3. Changes to Controller Tests

If you’re testing what your template renders in your controller, you are doing it wrong. A simple change to your template will leave you with sleepless nights, hunting down the culprit. That’s why, in Rails 5,assert_template is deprecated. However, you can continue using assert_select to check if a specific DOM element is present.

If you’ve been testing the instance variables inside a controller method, you should note that assigns is also going away.

there are two more important links for the same as-

  1. sitepoint link
  2. Blog eng link

Thanks for your time

Wait for your valuable comment.

Have a nice day!!!

What are the positive aspects of Rails?


Rails provides many features like

Scaffolding: Rails have an ability to create scaffolding or temporary code automatically.
CoC (Convention over configuration): Unlike other development framework, Rails does not require much configuration, if you follow the naming convention carefully

Meta-programming: Rails uses code generation but for heavy lifting it relies on meta-programming. Ruby is considered as one of the best language for Meta-programming.
Active Record: It saves object to the database through Active Record Framework. The Rails version of Active Record identifies the column in a schema and automatically binds them to your domain objects using meta-programming

Three environments: Rails comes with three default environment testing, development, and production.
Built-in-testing: It supports code called harness and fixtures that make test cases to write and execute.
———————————————————————————-

download

Explain what is the role of sub-directory app/controllers and app/helpers?

App/controllers: A web request from the user is handled by the Controller. The controller sub-directory is where Rails looks to find controller classes
App/helpers: The helper’s sub-directory holds any helper classes used to assist the view, model and controller classes.

for more detail visit http://career.guru99.com/top-34-ruby-on-rail-interview-questions/

Have a nice day!!!