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 solve Authentication issue with Devise & Active Admin in rails 5


Whenever I am clicking http://localhost:3000/admin , first it asks for login with user and then with admin credential.

I am using Devise and recently added Active Admin, which created a separate table of admin_users to keep admins.

All works fine with Active Admin when I try to log in and browse around. However, my application controller has this for general users

After googling a lot from last evening I got my issue solved with the help of StackOverflow answer which I voted Up.

In config/initializers/active_admin.rb you can add the following:

config.skip_before_action :authenticate_user!

You can also use the DSL provided to modify the ActiveAdmin controller: http://activeadmin.info/docs/8-custom-actions.html#modify_the_controller

Note: For Rails versions before 5.0 you will want to use skip_before_filter.

source of the blog is presented here.
Hope will help for others!!!

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"
}
]

Open html page from assets using WebView in ionic2


Angular2 unsafe resource URL in iFrame with DomSanitationService

after doing a lot of googling, I came to solve my issue by self.

here is waht I did to get it working-

  1. Remove complete get_page.servise.js,
  2. commented import of this file// import {GetPageService} from “./get_page.service”;
  3. Removed _gps: GetPageService, from constructor.
  4. removed ngOnInit() function

ngOnInit() {
    this._gps.getPage().subscribe(
        (data)=>{
          this.page = this.sanitizer.bypassSecurityTrustResourceUrl(data);
          //console.log(this.page);
        }
    )
  }
  1. Most important-

    Change all private as public in constructor as-

    constructor( public sanitizer: DomSanitizationService, public nav: NavController, navParams: NavParams )

My controller is as —

import {SafeResourceUrl, DomSanitizationService} from '@angular/platform-browser';
import { NavController, NavParams } from 'ionic-angular';
import { Component, ViewChild } from '@angular/core';
import { Http } from '@angular/http';
import { Slides } from 'ionic-angular';


@Component({
  templateUrl: 'build/pages/view/view.html',
})

export class ViewPage {

  //url: any;
  page: any;
  @ViewChild('mySlider') slider: Slides;

  constructor( public sanitizer: DomSanitizationService, public nav: NavController, navParams: NavParams ) {
    let url = navParams.get('url');
    this.page = this.sanitizer.bypassSecurityTrustResourceUrl(url);
    // this.url = navParams.get('url'); 
    // console.log(this.url);
  }
}

View page is still same as-

<iframe class= "webPage" [src]='page' width="100%" height="250" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen>

Hope this will help you too.

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.

Why does (click) function not work sometimes in ionic / angular


This is very common problem, if you are using

tags then it may not work.

I some cases It works for two- tree clicks after that is won’t.

I was stuck in the same issue. after digging much i got solution for the same here.

Just I exchanged div with button tag

tags with and it work for me.

It was my code then-

Explore
</div>

It is now with working condition-

Explore

Note: <div> and <span> does not work good.

We can also see on stack.

Thanks

Hope it will help you to.

Have a nice day.

we can also see Here

How to open Simple PopUp in ionic-2


Hi all,

I am also working on ionic2 and was in the need to implement “PopUp” window in my existing application. I try many for that by does not get my task accomplished, finally i did something like this-

  • pop-up.html
    <button block dark (click)="showAlert()">Help Window</button>
  • pop-up.ts
    import { Component } from ‘@angular/core’; import { Alert, NavController, NavParams} from ‘ionic-angular’;@Component({ templateUrl: ‘build/pages/pop-up/pop-up.html’, })export class PopUpPage { static get parameters() { return [[NavController]]; } constructor(private nav: NavController) { this.nav = nav; }

    showAlert() {
      let alert = Alert.create({
        title: 'Help Window!',
        subTitle: 'Mindfulness is here for you and your soul. We are intended to stablish your connection to All Mighty.',
        buttons: ['Cancle']
      });
      this.nav.present(alert);
    }
    

    }

This work for me.

screen-shot-2016-09-09-at-3-13-07-pm

Hope will help you…

we can also view here

 

Web View in ionic 2 (Open simple html files from assets )


After wondering a lot to have ionic WebView, I come to get this task done by using these steps-

  1. install inappbrowser in the application by using this path, and follow the steps to get install.
  2. make sure you have all html, images and css in assets directories
  3. for eg-
  4. www/assets/html.
  5. www/assets/css.  
  6. www/assets/images etc..
  7. open file where your want to access the view from assets and type

<a class=”item” href=”#” onclick=”window.open(‘http://www.nraboy.com/contact&#8217;, ‘_self’, ‘location=yes’); return false;”>
External Link Profile
</a>
<a class=”item” href=”#” onclick=”window.open(‘http://localhost:8100/ionic-lab&#8217;, ‘_self’, ‘location=yes’); return false;”>
Local Link of app
</a>

<a class=”item” href=”#” onclick=”window.open(‘/assets/challenge/my-page.html’,’_self’);”>
Open page
</a>

  1. make sure that link format must be in bellow format as-
    var ref = cordova.InAppBrowser.open(url, target, options);
  2. where –
    • ref: Reference to the InAppBrowser window when the target is set to '_blank'. (InAppBrowser)
    • url: The URL to load (String). Call encodeURI() on this if the URL contains Unicode characters.
    • target: The target in which to load the URL, an optional parameter that defaults to _self. (String)
      • _self: Opens in the Cordova WebView if the URL is in the white list, otherwise it opens in the InAppBrowser.
      • _blank: Opens in the InAppBrowser.
      • _system: Opens in the system’s web browser.
    • options: Options for the InAppBrowser. Optional, defaulting to: location=yes. (String)
  3. read the document carefully which will help you to get the task done.

Have a nice day!!!