Grant privileges to all tables in a database for postgresql

June 17th, 2009

Grant privileges to all tables in a database (select, update, insert, delete)

Eg:( Creating a read-only user in postgres)

–Function to grant access(select,insert,update,delete) to users

CREATE FUNCTION pg_grant(TEXT, TEXT, TEXT, TEXT)
RETURNS integer AS ‘
DECLARE obj record;
num integer;
BEGIN
num:=0;
FOR obj IN SELECT relname FROM pg_class c
JOIN pg_namespace ns ON (c.relnamespace = ns.oid) WHERE
relkind in (”r”,”v”,”S”) AND
nspname = $4 AND
relname LIKE $3
LOOP
EXECUTE ”GRANT ” || $2 || ” ON ” || obj.relname || ” TO ” || $1;
num := num + 1;
END LOOP;
RETURN num;
END;
‘ LANGUAGE plpgsql SECURITY DEFINER;

–Function to revoke access(select,insert,update,delete) from users

CREATE FUNCTION pg_revoke(TEXT, TEXT, TEXT, TEXT)
RETURNS integer AS ‘
DECLARE obj record;
num integer;
BEGIN
num:=0;
FOR obj IN SELECT relname FROM pg_class c
JOIN pg_namespace ns ON (c.relnamespace = ns.oid) WHERE
relkind in (”r”,”v”,”S”) AND
nspname = $4 AND
relname LIKE $3
LOOP
EXECUTE ”REVOKE ” || $2 || ” ON ” || obj.relname || ” FROM ” || $1;
num := num + 1;
END LOOP;
RETURN num;
END;
‘ LANGUAGE plpgsql SECURITY DEFINER;

–Create users for your database

CREATE USER userreadonly WITH PASSWORD ‘userr3ad0nly’;
CREATE USER userall WITH PASSWORD ‘usersh0pa11′;

–Grant respective access to users

select pg_grant(’
userreadonly ','select','%','public');
select pg_grant(’
userall ','select,insert,update,delete','%','public');

You might need to create lang for plpgsql if you had not done so

createlang plpgsql yrdatabasename

[Post to Twitter]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to StumbleUpon] 

Bhushan Ahire Security , ,

Transperent div for all browser

May 26th, 2009

if (b.ie)
{
var filter = this.element.style.filter.replace(/alpha\s*\(\s*opacity\s*=\s*[0-9\.]{1,3}\)/, ”);
this.element.style.filter = filter + ‘alpha(opacity=’ + parseInt(ht * 100, 10) + ‘)’;
}
else
{
this.element.style.opacity = ht;
}
this.element.style.visibility = ‘visible’;
this.element.style.display = ‘block’
}

[Post to Twitter]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to StumbleUpon] 

Bhushan Ahire Rails, Uncategorized , , ,

Get location from IP address in Ruby On Rails for free….

May 20th, 2009

Find below the code for finding location from IP address using IP location tools.

require 'net/http'
require 'rexml/document'
include REXML

class MapsController < ApplicationController
	def index
		@location = locateIp()

	end

	def locateIp
		ip = request.remote_ip
		ips = ip.to_s
		url = "http://iplocationtools.com/ip_query.php?ip="+ips

		xml_data = Net::HTTP.get_response(URI.parse(url)).body

                xmldoc = REXML::Document.new(xml_data)

		# Now get the root element
		root = xmldoc.root
		city = ""
		regionName = ""
		countryName = ""

		# This will take country name...
		xmldoc.elements.each("Response/CountryName") {
		|e| countryName << e.text
	    }

		# Now get city name...
		xmldoc.elements.each("Response/City") {
   		|e| city << e.text
	    }

		# This will take regionName...
		xmldoc.elements.each("Response/RegionName") {
   		|e| regionName << e.text
	    }

     	ipLocation = city +", "+regionName+", "+countryName

	 return ipLocation
   end #end of method locateIp

end

[Post to Twitter]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to StumbleUpon] 

Bhushan Ahire Rails, Security, ruby , , ,

Install and Configure FTP Server in Amazon EC2 instance

April 15th, 2009

For many users, running FTP Sever in Amazon EC2 instance is headache at the first time. You need to experiment before being able to transfer data. The main problems are Ingress firewall in Amazon environment and NAT traversal.

Here I’m using vsftp (vsfptd) Server, which is one of the most popular and easy to configure. The instance is running from base Fedora 4 AMI but the setup should be identical to other Red Hat based distros.

Install vsftpd FTP server, if not installed earlier:

# yum install vsfptd

Its upto you which FTP method i.e. Active or Passive you want to use. The problem with active mode is that your computer is sending a request out of port 21 when all of a sudden, the server attempts to initiate a request with your computer on port 20. Since communication on port 21 does not imply communication on port 20, it appears as if some unauthorized host has attempted to initiate a new connection with your computer. Kind of sounds like a hack right? Your firewall may think so too (or your NAT router may have no idea to which computer to route the request). Active mode is not used as default method of ftp transfer in many clients these days.

On the other hand, as the Ingress firewall is running in AWS, from the firewall’s standpoint, to support passive mode FTP the following communication channels need to be opened:

FTP server’s port 21 from anywhere (Client initiates connection).
FTP server’s port 21 to ports > 1023 (Server responds to client’s control port).
FTP server’s ports > 1023 from anywhere (Client initiates data connection to random port specified by server).
FTP server’s ports > 1023 to remote ports > 1023 (Server sends ACKs (and data) to client’s data port).

That second part is the problem: FTP server listens on a random port and hands that back to the client, so the client initiates a connection to a random server port, which you must allow.

Opening up all ports > 1023 isn’t so good for security. But what you can do is allow the ports through the distributed firewall and then setup your own filtering inside your instance. Instead, you would better open a fixed number of ports (such as 1024 to 1048) and configure your FTP Server to only use that ports.

Check whether required ports are open or not in your EC2 security group. (if you are unaware about security group, it should be ‘defaul’ unless you created a new one).

# ec2-describe-group

This command will print all ports which are currently open. If you dont find port 20,21,1024-1048 then you need to open these ports but if you dont find the command itself i.e.
# ec2-describe-group
-bash: ec2-describe-group: command not found

You need to install ec2 command line tools. You can find them here and the instructions to setup/configure can be found here.

Open the ports now:

# ec2-authorize default -p 20-21
# ec2-authorize default -p 1024-1048

Here, ‘default’ is the name of security group. You can also open ports for specific IPs. For ease of use, you better install ElasticFox, a firefox extension to manage EC2 stuff. you can find more about it here.

At this moment, you can start your FTP server and if you try to connect it, the process will get failed. By checking logs, you should find something like:

Status: Connected
Status: Retrieving directory listing…
Command: PWD
Response: 257 “/” is current directory.
Command: TYPE A
Response: 200 Type set to A
Command: PASV
Response: 227 Entering Passive Mode (216,182,238,73,129,75).
Command: LIST
Error: Transfer channel can’t be opened. Reason: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
Error: Could not retrieve directory listing

Time to configure vsftpd.conf file:
# vi /etc/vsftpd/vsftpd.conf
—Add following lines at the end of file—
pasv_enable=YES
pasv_min_port=1024
pasv_max_port=1048
pasv_address=Public IP of your instance

Put public IP of your EC2 instance and then Save the file. Now restart the server:

# /etc/init.d/vsftpd restart

[Post to Twitter]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to StumbleUpon] 

Bhushan Ahire Amazon EC2, Security , , , , , ,

Install Git on MAC Tiger (10.4.11)

April 14th, 2009

I downloaded and compiled the latest Git version, 1.6.2.3 like so:

curl -O http://kernel.org/pub/software/scm/git/git-1.6.2.3.tar.gz
tar jxvf git-1.6.2.3.tar.gz
cd git-1.6.2.3
make prefix=/usr/local all
make prefix=/usr/local test && echo $?
sudo make prefix=/usr/local install

When the compile was done, it gave me output like this:

!! You have installed git-* commands to new gitexecdir.
!! Old version git-* commands still remain in bindir.
!! Mixing two versions of Git will lead to problems.
!! Please remove old version commands in bindir now.

I simply did:

cd /usr/local/bin/
ls -latr | grep git

Which gave me an ordered list of all the git binaries installed. The ones at the end all had today’s date on them, so I knew those were the new versions. The rest I could whack. The ones I could keep were git-upload-pack, git-upload-archive, git-receive-pack, git, git-shell, git-cvsserver, and gitk. The rest I removed like so:

sudo rm git-var git-update-server-info git-unpack-file git-ssh-upload git-ssh-push git-ssh-pull git-ssh-fetch git-show-index git-send-pack git-peek-remote git-patch-id git-pack-redundant git-mktree git-mktag git-merge-tree git-merge-recursive git-merge-index git-local-fetch git-index-pack git-imap-send git-http-push git-http-fetch git-hash-object git-fetch-pack git-fast-import git-daemon git-convert-objects git-bisect git-write-tree git-whatchanged git-verify-tag git-verify-pack git-update-ref git-update-index git-unpack-objects git-tar-tree git-tag git-symbolic-ref git-svnimport git-svn git-submodule git-stripspace git-status git-stash git-show-ref git-show-branch git-show git-shortlog git-sh-setup git-send-email git-runstatus git-rm git-revert git-rev-parse git-rev-list git-reset git-rerere git-request-pull git-repo-config git-repack git-remote git-relink git-reflog git-rebase--interactive git-rebase git-read-tree git-quiltimport git-push git-pull git-prune-packed git-prune git-parse-remote git-pack-refs git-pack-objects git-name-rev git-mv git-mergetool git-merge-subtree git-merge-stupid git-merge-resolve git-merge-ours git-merge-one-file git-merge-octopus git-merge-file git-merge-base git-merge git-mailsplit git-mailinfo git-ls-tree git-ls-remote git-ls-files git-lost-found git-log git-instaweb git-init-db git-init git-gui git-grep git-get-tar-commit-id git-gc git-fsck-objects git-fsck git-format-patch git-for-each-ref git-fmt-merge-msg git-filter-branch git-fetch--tool git-fetch git-diff-tree git-diff-index git-diff-files git-diff git-describe git-cvsimport git-cvsexportcommit git-count-objects git-config git-commit-tree git-commit git-clone git-clean git-citool git-cherry-pick git-cherry git-checkout-index git-checkout git-check-ref-format git-check-attr git-cat-file git-bundle git-branch git-blame git-archive git-archimport git-apply git-annotate git-am git-add--interactive git-add gitjour

Then I just had to go back and install the manpages for the new version like so:

curl -O http://kernel.org/pub/software/scm/git/git-manpages-1.6.2.3.tar.bz2
sudo tar xjv -C /usr/local/man -f git-manpages-1.6.2.3.tar.bz2

And, low and behold, I was now running git 1.6.2.3!

[Post to Twitter]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to StumbleUpon] 

Bhushan Ahire MAC Tiger, git , ,

Unbricker for New GENE (HTC 8XXX), Stucks at Bootloader

March 12th, 2009

Thats worked unbricker for newer Genes, broken by old gene_hspl.

Using:

1. Unpack all in some folder.
2. Press and HOLD “Camera” button and turn on device.
3. If you see 3-colored screen, release “Camera” button, else try again.
4. Kill ActiveSync on computer - Press Ctrl+Shift+Esc, found “wcescomm.exe” process and terminate it.
5. Connect USB-cable to device.
(In the left bottom corner of the screen to appear the text “USB”)
6. Run mtty1_42.exe programm, and press button “USB”.
7. In the opened window type the text:

Code:
       set 32 1

Press Enter. (You must type this text by hand, not copy/paste)
8. After you will see answer from device in window.
9. Type in window that text:

Code:
      ls boot.bin

Press and HOLD “Camera” button on device, and press Enter in mtty window.
10. After a while the device screen becomes white.
Wait 2-3 second, and release “Camera” button.
11. Close mtty programm.
12. Run RomUpdateUtility.exe programm and follow her instruction.

If device will not flashed, try once from first.
Gene Unbricker for New GENE

[Post to Twitter]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to StumbleUpon] 

Bhushan Ahire Pocket PC, WM6 , , ,

See your most frequently used commands

March 10th, 2009
history | awk '{print $2}' | awk 'BEGIN {FS="|"}{print $1}' | sort | uniq -c | sort -n | tail | sort -nr

[Post to Twitter]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to StumbleUpon] 

Bhushan Ahire Uncategorized ,

Generating ZIP files via Ruby on Rails using rubyzip

March 3rd, 2009
gem install rubyzip

Then, in the model that I’m using to generate the zip bundles, I add a couple “require” statements:

require 'zip/zip'
require 'zip/zipfilesystem'

class Album < ActiveRecord::Base
  (...)
end

Next, I added a class method called bundle, which when called will use rubygem to generate the zip file. Note: the “permalink” attributes of Album and Artist are populated when an object of those models is created. I’m using them because it makes for nice filenames, too.

# create a zipped archive file of all the tracks in an album
def bundle(name = self.permalink, set = self.artist.permalink)
   bundle_filename = "#{RAILS_ROOT}/public/uploads/#{set}-#{name}.zip"

   # check to see if the file exists already, and if it does, delete it.
   if File.file?(bundle_filename)
     File.delete(bundle_filename)
   end 

   # set the bundle_filename attribute of this object
   self.bundle_filename = "/uploads/#{set}-#{name}.zip"

   # open or create the zip file
   Zip::ZipFile.open(bundle_filename, Zip::ZipFile::CREATE) {
     |zipfile|
     # collect the album's tracks
     self.tracks.collect {
       |track|
         # add each track to the archive, names using the track's attributes
         zipfile.add( "#{set}/#{track.num}-#{track.filename}", "#{RAILS_ROOT}/public#{track.public_filename}")
       }
   }

   # set read permissions on the file
   File.chmod(0644, bundle_filename)

   # save the object
   self.save
end

Next I added a method in my controller:

def create_bundle
   album = Album.find(params[:id])
   album.bundle
   flash[:notice] = 'Album was successfully zipped.'
   redirect_to album_url(album.artist, album)
end

And edit my routes.rb accordingly:

map.create_bundle 'create_bundle/:id', :controller => 'albums', :action => 'create_bundle'

Now it’s just a matter of creating a link in the view for the admin to click whenever he/she wants to generate the zip file:

<%= link_to('Create Album Zip', create_bundle_path(@album)) %>

…and a link for the user to click to download the zip file if it exists:

<% unless @album.bundle_filename.nil? %>
<%= link_to "Download Album Zip", @album.bundle_filename %>
<% end %>

That’s it! Refer to the rubyzip documentation for more info.

[Post to Twitter]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to StumbleUpon] 

Bhushan Ahire Rails, ruby , ,

Keep either file in merge conflicts with git

February 26th, 2009

So, the scenario is: you’re in the middle of a merge, and you want to keep one file or the other.

$ git merge master
Auto-merged _layouts/default.html
CONFLICT (content): Merge conflict in _layouts/default.html
Auto-merged index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.

There’s two unmerged files here. According to the git checkout manpage, there’s a --theirs and --ours options on the command. The former will keep the version of the file that you merged in, and the other will keep the original one we had.

The following commands will keep the original file for index.html, and then use the merged in file only for _layouts/default.html.

git checkout –ours index.html
git checkout –theirs _layouts/default.html

Sadly, these options are only in Git versions 1.6.1 and up. If you have an older version and don’t feel like upgrading, there’s ways to get around this. To emulate --theirs, we’d do:

git reset — _layouts/default.html
git checkout MERGE_HEAD — _layouts/default.html

And for --ours:

git reset — index.html
git checkout ORIG_HEAD — index.html

Of course, once you’ve got the conflicts worked out, git add whatever changes need to be added in, and git commit away. If you’ve run into other problems with merging that could possibly help out others, comment away!



referred from http://gitready.com/advanced/2009/02/25/keep-either-file-in-merge-conflicts.html

[Post to Twitter]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to StumbleUpon] 

Bhushan Ahire Rails, git , , ,

Setting up a new remote git repository

February 19th, 2009

For the impatient

Set up the new bare repo on the server:

$ ssh myserver.com
Welcome to myserver.com!
$ mkdir /var/git/myapp.git && cd /var/git/myapp.git
$ git --bare init
Initialized empty Git repository in /var/git/myapp.git
$ exit
Bye!

Add the remote repository and push:

$ cd ~/Sites/myapp
$ git remote add origin ssh://myserver.com/var/git/myapp.git
$ git push origin master

Set the local master branch to track the remote branch.

Read further for a step-by-step explanation of what’s going on.

Pre-flight sanity check

Setting up a remote repository is fairly simple but somewhat confusing at first. Firstly, let’s check out what remote repositories are being tracked in our git repo:

$ cd ~/Sites/myapp
$ git remote

None. Looking good. Now let’s list all the branches:

$ git branch -a
* master

Just one branch, the master branch. Let’s have a look at .git/config:

$ cat .git/config
[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true

A pretty bare-minimum config file.

Creating the bare remote repository

Before we can push our local master branch to a remote repository we need to create the remote repository. To do this we’ll ssh in and create it on the server:

$ ssh myserver.com
Welcome to myserver.com!
$ cd /var/git
$ mkdir myapp.git
$ cd myapp.git
$ git --bare init
Initialized empty Git repository in /var/git/myapp.git
$ exit
Bye!

A short aside about what git means by bare: A default git repository assumes that you’ll be using it as your working directory, so git stores the actual bare repository files in a .git directory alongside all the project files. Remote repositories don’t need copies of the files on the filesystem unlike working copies, all they need are the deltas and binary what-nots of the repository itself. This is what “bare” means to git. Just the repository itself.

Adding the remote repository to our local git repository configuration

Now that we’ve created the remote repository we’ll add it to our local repository as a remote server called “origin” using git remote add, which is just a nicer way of updating our config file for us:

$ git remote add origin ssh://myserver.com/var/git/myapp.git

Let’s see what it added to the config file:

[core]
  repositoryformatversion = 0
  filemode = true
  bare = false
  logallrefupdates = true
[remote "origin"]
  url = ssh://myserver.com/var/git/myapp.git
  fetch = +refs/heads/*:refs/remotes/origin/*

We now have a remote repository “origin” that will fetch all of it’s refs/heads/* branches and store them in our local repo in refs/remotes/origin/* when a git fetch is performed.

Pushing to the remote repository

The time has come to push our local master branch to the origin’s master branch. We do that using the git push command.

$ git push origin master
updating 'refs/heads/master'
  from 0000000000000000000000000000000000000000
  to   b379203bc187c2926f44a71eca3f901321ea42c6
 Also local refs/remotes/origin/master
Generating pack...
Done counting 1374 objects.
Deltifying 1374 objects...
 100% (1374/1374) done
Writing 1374 objects...
 100% (1374/1374) done
Total 1374 (delta 89), reused 0 (delta 0)
refs/heads/master: 0000000000000000000000000000000000000000 -> b379203bc187c2926f44a71eca3f901321ea42c6

and that’s all, folks. Further pushes can be done by repeating the git push command.

Now you can tell your co-conspirators to:

$ git clone ssh://myserver.com/var/git/myapp.git

and push and pull to your heart’s content.

Track the remote branch

You can specify the default remote repository for pushing and pulling using git-branch’s track option. You’d normally do this by specifying the --track option when creating your local master branch, but as it already exists we’ll just update the config manually like so:

[branch "master"]
  remote = origin
  merge = refs/heads/master

Now you can simply git push and git pull.

Sharing the remote repository with the world

If you want to set it up as a public repository be sure to check out the Git manual’s chapter on public git repositories.

Working with remote repository branches

git remote show is used to inspect a remote repository. It goes and checks the remote repository to see what branches have been added and removed since the last git fetch.

Doing a git remote show at the moment only shows us the remote repo’s master branch which we pushed earlier:

$ git remote show origin
* remote origin
  URL: ssh://myserver.com/var/git/myapp.git
  Tracked remote branches
    master

Let’s create a new local git repository and push to a new branch on the remote repository. We can then use git remote show to see the new remote branch, git fetch to mirror it into our local repo and git checkout --track -b to create a local branch to do some work on it.

We’ll start by creating a new local repo and pushing some code to a new branch in the remote repository.

$ mkdir /tmp/other-git
$ cd /tmp/other-git
$ git init
Initialized empty Git repository in /tmp/other-git
$ git remote add origin ssh://myserver.com/var/git/myapp.git
$ echo "Rails 2... woo" > afile
$ git add afile
$ git commit -m "Added afile" 
Created initial commit 0ac9a74: Added afile
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 something
$ git push origin master:refs/heads/dev/rails-2
updating 'refs/heads/rails-2' using 'refs/heads/master'
  from 0000000000000000000000000000000000000000
  to   0ac9a7457f4b21c9e058d4c54d262584bf35e528
 Also local refs/remotes/origin/rails-2
Generating pack...
Done counting 3 objects.
Deltifying 3 objects...
 100% (3/3) done
Writing 3 objects...
 100% (3/3) done
Total 3 (delta 0), reused 0 (delta 0)
Unpacking 3 objects...
 100% (3/3) done
refs/heads/rails-2: 0000000000000000000000000000000000000000 -> 0ac9a7457f4b21c9e058d4c54d262584bf35e528

Now let’s switch back to our old git repository and see if it detects the new branch on the remote repository:

$ git remote show origin
* remote origin
  URL: ssh://myserver.com/var/git/myapp.git
  New remote branches (next fetch will store in remotes/origin)
    dev/rails-2
  Tracked remote branches
    master

Let’s update our mirror of the remote repository by doing a git fetch:

$ git fetch
* refs/remotes/origin/master: storing branch 'dev/rails-2' of ssh://myserver.com/var/git/myapp.git
  commit: b379203
$ git remote show origin
* remote origin
  URL: ssh://myserver.com/var/git/myapp.git
  Tracked remote branches
    master
    dev/rails-2

We should now be able to see this in a our list of remote branches:

$ git branch -a
* master
origin/dev/rails-2
origin/master

If we then wanted to do some work on this remote dev/rails-2 branch we create a new local tracking branch like so:

$ git checkout --track -b dev/rails-2 origin/dev/rails-2
Branch dev/rails-2 set up to track remote branch refs/remotes/origin/dev/rails-2.
Switched to a new branch "dev/rails-2"

To keep up-to-date and push new changesets we simply use git push and git pull when working in the local dev/rails-2 branch.

Also notice, like we manually changed for master, .git/config has a new entry for this new tracking branch:

[branch "dev/rails-2"]
  remote = origin
  merge = refs/heads/dev/rails-2

[Post to Twitter]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to StumbleUpon] 

Bhushan Ahire Rails, git , , ,