using Ruby to check that username exists in sqlite3 database - ruby

I am new to ruby. I am trying use ruby accept username from user and check it against sqlite3 database to see if it exists. if it exists, then ask user to input a different username. I have tried below code but it doesn't work. Please help me.
The sqlite3 table is "cpu_dues" and the column I am checking against is "user_name". Then I am accepting a variable "user" to compare with values in the database.
require 'sqlite3'
print "Enter your Username: "
user = gets.chomp().to_s
db = SQLite3::Database.open 'ipu_db.db'
db.results_as_hash = false
user_exist = [db.execute( "SELECT user_name FROM ipu_dues WHERE user_name = ('#{user}')"), 1]
if user_exist[0] = user
puts "Keep asking for username"
else
puts "accept username and carry on"
end

Related

How to add another windows user to MS Dynamics NAV valid user?

I installed MS Dynamics NAV from my windows admin account and It's running successfully on admin login. But when I login from another account and start NAV(2016), It shows :
you do not have access to microsoft dynamics nav .verify that you have been setup as a valid user in ms dynamics NAV.
I can't install NAV setup from my windows account as It don't have permission to install anything.
I am totally new to it, need help.
Step 1 - You will need the Windows Security ID or SSID
Open powershell and paste the below code
$objUser = New-Object System.Security.Principal.NTAccount("YourDomain\Your ID")
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSID.Value
Replace YourDomain\Your ID with your Your Domain and USER ID.
Run the code and in the output, you will find the SSID.
STEP 2 - ENTER USER Details in NAVISION Database with Roles.
Open SQL Server Management Studio.
In My Case the database that i want to get access is Demo Database NAV (7-1).
Click on New Query and paste below listed command in the query window.
USE [DATABASE NAME]
DECLARE #USERSID uniqueidentifier, #WINDOWSSID nvarchar(119), #USERNAME nvarchar(50), #USERSIDTXT varchar(50)
SELECT NEWID()
SET #USERNAME = 'YourDomain\Your ID'
SET #USERSID = NEWID()
SET #USERSIDTXT = CONVERT(VARCHAR(50), #USERSID)
SET #WINDOWSSID = 'Your SSID'
INSERT INTO [dbo].[User]
([User Security ID],[User Name],[Full Name],[State],[Expiry Date], [Windows Security ID],[Change Password],[License Type],[Authentication Email])
VALUES
(#USERSID,#USERNAME,'',0,'1753-01-01 00:00:00.000',#WINDOWSSID,0,0,'')
INSERT INTO [dbo].[User Property]
([User Security ID],[Password],[Name Identifier],[Authentication Key], [WebServices Key],[WebServices Key Expiry Date],[Authentication Object ID])
VALUES
(#USERSID,'','','','','1753-01-01 00:00:00.000','')
INSERT INTO [dbo].[Access Control]([User Security ID],[Role ID],[Company Name])
VALUES
(#USERSID,'SUPER','')
GO
Replace
DATABASE NAME - with your database name
YourDomain\Your ID - with your Domain Name & User Name
Your SSID - with SSID as copied in STEP 1
The Query provide SUPER Role to user, if required you can change the Role in the Last part of the query.
Go to SQL Server Management Studio
Right click on database you are using , select new query and copy paste below syntax:
delete from [dbo].[User]
press F5 and restart. It will help you .
Quick way option with powershell, you should change some configurations.
For NAV 2016
$appUser = "XXX\XXX"; # User Name
$appUserFullName = "XXXXXxxxXX"; # FullName
$dataSource = "192.168.100.XX"; # SQL SERVER IP
$user = "sa"; # USERNAME
$pwd = "XXxxXX"; # SA Password
$database = "NAVERP"; # Database
$connectionString = "Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;";
$connection = New-Object System.Data.SqlClient.SqlConnection;
$connection.ConnectionString = $connectionString;
$objUser = New-Object System.Security.Principal.NTAccount($appUser)
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$sqlCommandText ="
USE NAVERP
DECLARE #USERSID uniqueidentifier, #WINDOWSSID nvarchar(119), #USERNAME nvarchar(50), #USERSIDTXT varchar(50), #FullName as varchar(50)
SELECT NEWID()
SET #USERNAME = '$appUser'
set #FullName = '$appUserFullName'
SET #USERSID = NEWID()
SET #USERSIDTXT = CONVERT(VARCHAR(50), #USERSID)
SET #WINDOWSSID = '$strSID'
INSERT INTO [dbo].[User]
([User Security ID],[User Name],[Full Name],[State],[Expiry Date],[Windows Security ID], [Change Password],[License Type],[Authentication Email],[Contact Email])
VALUES
(#USERSID,#USERNAME,#FullName,0,'1753-01-01 00:00:00.000',#WINDOWSSID,0,0,'','');
INSERT INTO [dbo].[User Property]
([User Security ID],[Password],[Name Identifier],[Authentication Key], [WebServices Key],[WebServices Key Expiry Date],[Authentication Object ID])
VALUES
(#USERSID,'','','','','1753-01-01 00:00:00.000','');
INSERT INTO [dbo].[Access Control]([User Security ID],[Role ID],[Company Name],[App ID],Scope)
VALUES
(#USERSID,'SUPER','',cast(cast(0 as binary) as uniqueidentifier),0);
";
$connection.Open();
$command = $connection.CreateCommand();
$command.CommandText = $sqlCommandText;
$command.ExecuteNonQuery();
$connection.Close();
$sqlCommandText

Create Postgresql database in Heroku with Ruby (without Rails)

I'm currently hosting a simple Ruby script that stores URLs and Scores and saving them to YAML. However, I'd like to save to a Postgresql database instead since the yaml file is deleted every time I restart the app. Here's the error I'm getting in Heroku:
could not connect to server: No such file or directory (PG::ConnectionBad)
Here's an example script that works locally, but throws me the above error in Heroku:
require 'pg'
conn = PG.connect( dbname: 'template1' )
res1 = conn.exec('SELECT * from pg_database where datname = $1', ['words'])
if res1.ntuples == 1 # db exists
# do nothing
else
conn.exec('CREATE DATABASE words')
words_conn = PGconn.connect( :dbname => 'words')
words_conn.exec("create table top (url varchar, score integer);")
words_conn.exec("INSERT INTO top (url, score) VALUES ('http://apple.com', 1);")
end
Thanks in advance for any help or suggestions!
Assuming you have created a Postgres database using the Heroku toolchain via heroku addons:add heroku-postgresql:dev (or the plan of your choice) you should have a DATABASE_URL environmental variable that contains your connection string. You can check that locally through heroku pg:config.
Using the pg gem (docs: http://deveiate.org/code/pg/PG/Connection.html) - and modifying the example from there to suit -
require 'pg'
# source the connection string from the DATABASE_URL environmental variable
conn = PG::Connection.new(ENV['DATABASE_URL'])
res = conn.exec_params('create table top (url varchar, score integer;")
Update: A slightly more complete example for the purposes of error handling:
conn = PG::Connection.new(ENV['TEST_DATABASE_URL'])
begin
# Ensures the table is created if it doesn't exist
res = conn.exec("CREATE TABLE IF NOT EXISTS top (url varchar, score integer);")
res.result_status
rescue PG::Error => pg_error
puts "Table creation failed: #{pg_error.message}"
end

How to get properties of Authentification Alias on WAS 7 using wsadmin

I created a script in Jython which extracts some properties of a Data Source from WAS 7. One of theese properties is the Authentification Alias. I know that the password is crypted, but project has a semididactical purpose so the focus is on retriving the username and password, not to hack something.
How can I extract the properties of the Authentification Alias, i mean the username and the password?
Thanks in advance!
I solved the problem. :) Let's start with the beginning.
You have to find security.xml (WAS_HOME/AppServer/profiles/Profile_Name/config/cells/Cell_Name/security.xml) file and search in it the Authentication Alias.
Keep the line that contains the Auth Alias in a variable called Line and then extract the username, password and description.
After that you have to decrypt your password with a XOR algorithm, and write the variables in a file as a list. Ex: AuthDataAlias = [\ ['AuthAlias', 'username', 'password', 'description'] ]
Code:
import sys, java, java.io, java.lang, base64, binascii
resFile="resources.res"
def search ( alias, file ):
f=open(file)
lines=f.readlines()
for line in lines:
poz = line.find('/'+alias)
if poz > 0:
Line = line
break
user = Line[Line.find('userId=')+8:Line.find('\" password')]
password = Line[Line.find('password=')+15:Line.find('\" description')]
password = decrypt(password)
description = Line[Line.find('description=')+13:Line.find('\"/>')]
write ( AuthAlias, user, password, description, resFile)
def write ( alias, user, password, desc, file ):
objItemFileOutputStream = java.io.FileOutputStream(file, 1) #apend la sfirsit fisier
objItemFileOutputStream.write('\n')
AuthList = "AuthDataAlias = [\\\n[\'"+alias+"\', \'"+user+"\', \'"+password+"\', \'"+desc+"\'] ]"
objItemFileOutputStream.write(AuthList)
def decrypt ( word ):
if not len(word) > 1: exit()
word = word.replace(':', '')
value1 = binascii.a2b_base64(word)
value2 = '_' * len(value1)
out = ''
for a, b in zip(value1, value2):
out = ''.join([out, chr(ord(a) ^ ord(b))])
return out
#MAIN
search ( AuthAlias, securityFile )
If anyone gets stuck with this issue feel free to post your questions and I will try to answer ASAP.

WebSphere wsadmin jython - prompting for password

I am looking for a way to prompt for password (that is, no input echo).
I am using jython in WebSphere's 7.0.0.19 wsadmin.
I've looked for it - it appears to be possible with import getpass or import termios (but I get "no module named ..." exception).
Any way to prompt for password anyway?
Thank you.
You can use the following code. It basically uses Java's console() if present (note that console may not be present all the time) else use raw_input() and password masking logic.
# if console is not available (ex: when invoked from a shell script or another java process)
# we need to fall back to use raw_input, but we should mask the password if we use it
import sys, thread, time, threading
from java.lang import String
def getPass(stream=None):
console = java.lang.System.console()
if console is None:
global p_stopMasking
if not stream:
stream = sys.stderr
try:
p_stopMasking = 0
threading.Thread(target=_doMasking,args=(stream,)).start()
password = raw_input()
p_stopMasking = 1
except Exception, e:
p_stopMasking = 1
print "Error Occured"
print e
exit()
else:
password = console.readPassword()
return String.valueOf(password)
def _doMasking(stream):
while not p_stopMasking:
stream.write("\010*")
#stream.write("\n")
stream.flush()
time.sleep(0.01)
def populateCredentials():
global username
global password
print 'Enter username:'
username = raw_input();
print 'Enter password:'
password = getPass(sys.stdout);
# start main
print 'start program...'
p_stopMasking= 1
username = None
password = None
populateCredentials()
print 'username is : ' + username
print 'password is : ' + password
The following also worked for me:
raw_input("")
myPass = raw_input("Please enter a password: ")
This isn't perfect because it doesn't mask the password, but it does work. For some reason, if you don't specify the first "raw_input" invocation then the script won't block on the second one.

Ruby PostgreSQL tutorials [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I am trying to write a ruby script that interacts with a PostgreSQL database. I am trying to piece together how to do this from the documentation, but a nice tutorial or sample code would work wonders to decrease the amount of time to get this working. If anyone has a link, some tips or has some code they could share I would be most grateful.
Edit, made this note more clear:
Note: this isn't to do with rails ActiveRecord, I am writing a Ruby script that will be involved in a program that is completely independent from Rails.
Please be more specific about what postgresql library you're using.
I'm going to assume the 'pg' gem, apart from ActiveRecord.
The project source has an html file that might be helpful.
Go to https://bitbucket.org/ged/ruby-pg/src/b477174160c8/doc/postgres.html
Then click "raw" at the upper right side of the html. Open the file in your web browser.
This sample code helps you connect (copied from the html file):
require "postgres"
conn = PGconn.connect("localhost", 5432, "", "", "test1")
# or: conn = PGconn.open('dbname=test1')
res = conn.exec("select * from a;")
The res object is a PGResult. Scroll down to that section in the html to see what methods you can call.
This link has a PGResult example:
http://rubydoc.info/gems/pg/0.10.0/PGresult
Excerpt:
require 'pg'
conn = PGconn.open(:dbname => 'test')
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c')
res.getvalue(0,0) # '1'
res[0]['b'] # '2'
res[0]['c'] # nil
I confirm, "postgres" package is outdated, you need "pg".
It tooks me lot of time just to get a basic select * from films working with ruby and postgres. As I am kind, here is my code:
postgres preparation (database=megatest user=roger pass=123456 table=films)
$ su postgres
psql
CREATE USER roger WITH PASSWORD '123456';
GRANT ALL PRIVILEGES ON DATABASE megatest to roger;
megatest=# GRANT SELECT ON films TO PUBLIC;
PG package preparation
sudo gem install pg
Ruby Code
require 'pg'
conn=PGconn.connect( :hostaddr=>"127.0.0.1", :port=>5432, :dbname=>"megatest", :user=>"roger", :password=>'123456')
# or for a non IP address :host => 'my.host.name.com' instead of hostaddr
# run the query
res = conn.exec("SELECT * FROM films")
# Ran only once in order to get field Name
fieldArray=res.fields()
fieldArray.each do |elem|
print "elem="+elem+"\n"
end
# print data from the query
res.each{ |row|
puts "Code="+row["code"] +" title="+row["title"] +" did="+row["did"] +" date_prod="+row["date_prod"] +" kind="+row["kind"] +" len="+row["len"]
}
Results
root#eblain-VirtualBox:/home/eblain/ruby# ruby postgresTest.rb
Code=UA502 title=Bananas did=105 date_prod=1971-07-13 kind=Comedy len=01:22:00
Code=UA503 title=Cowboy did=105 date_prod=1979-07-13 kind=Horror len=01:32:00
Code=UA544 title=YoBro did=105 date_prod=1981-07-13 kind=Action len=01:42:00
You only need to require the pg gem and establish the connection to the DB:
require 'pg'
# require 'active_record' # uncomment for not Rails environment
ActiveRecord::Base.establish_connection(:adapter => "postgresql",
:username => "username",
:password => "password",
:database => "database")
When you define models to inherit from ActiveRecord::Base they will use this database connection. Everything else should work like it does in Rails.
For parametrized SQL statements, you should use PGconn#exec_params, e.g.
conn = PGconn.new(:dbname => 'test')
conn.exec_params(
'INSERT INTO comedians (first_name, last_name) VALUES ($1, $2)',
['Louis', 'CK'])
conn.close
Source: http://deveiate.org/code/pg/PGconn.html
Look here for a complete list of parameters that can be passed to the PGconn constructor.

Resources