Skip to content

Instantly share code, notes, and snippets.

@nausik
Created March 22, 2015 14:29
Show Gist options
  • Select an option

  • Save nausik/5f2793a499f6907aebbd to your computer and use it in GitHub Desktop.

Select an option

Save nausik/5f2793a499f6907aebbd to your computer and use it in GitHub Desktop.
class Db
include Singleton
attr_accessor :db
def initialize
@db = SQLite3::Database.new "runcommend.sqlite3"
@db.results_as_hash = true
end
end
class Key
attr_reader :key, :expiration_date, :ip
def generate(params)
key = SecureRandom.hex 15
answer = Db.instance.db.execute "INSERT INTO Key(key_username, key_ip, key_generated_at, key_key) VALUES ('" + params[:username] + "', '" + key + "')"
end
end
class User
attr_reader :username, :password
@username = ""
@password = ""
def initialize(params)
@username = params[:username]
@password = params[:password]
end
def self.find(username)
users = Db.instance.db.execute "SELECT * From User WHERE user_username = '#{username}'"
if users.length === 0
nil
else
User.new({username: users[0]["user_username"], password: users[0]["user_password"]})
end
end
def self.create(params)
begin
answer = Db.instance.db.execute "INSERT INTO User(user_username, user_password) VALUES ('" + params[:username] + "', '" + params[:password] + "')"
nil
rescue SQLite3::Exception => e
return e.to_s
end
end
def to_json
'{"username": "' + @username + '",
"password": "' + @password + '"
}'
end
end
class Logic < Sinatra::Base
register Sinatra::Reloader
get '/user/:username' do |username|
user = User.find username
if user
user.to_json
else
"No such user"
end
end
get '/user/create/:username/:password' do |username, password|
user = User.create({username: username, password: password})
unless user.instance_of? String
'{"answer": "Succesfully created", "error": "0"}'
else
'{"answer":"' + user +'","error": "1"}'
end
end
get '/create_table' do
puts Db.instance.db.get_first_value 'SELECT SQLITE_VERSION()'
Db.instance.db.execute "CREATE TABLE User(
Id INTEGER PRIMARY KEY,
user_username TEXT,
user_password TEXT,
UNIQUE(user_username)
)"
Db.instance.db.execute "CREATE TABLE Key(
Id INTEGER PRIMARY KEY,
key_username TEXT,
key_key TEXT,
key_generated_at DATETIME,
key_ip, TEXT,
UNIQUE(key_key)
)"
Db.instance.db.execute "INSERT INTO User(user_username, user_password) VALUES ('nausik', '123qwe')"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment