Merge branch 'license'

This commit is contained in:
Yan
2017-11-29 18:07:27 +06:30
13 changed files with 465 additions and 305 deletions

View File

@@ -22,9 +22,12 @@ class ApplicationController < ActionController::Base
{ locale: I18n.locale }
end
def lookup_domain
if request.subdomain.present? && request.subdomain != "www"
@license = cache_license(ENV["SX_PROVISION_URL"], request.subdomain.downcase) # request.subdomain.downcase
def lookup_domain
if request.subdomain.present? && request.subdomain != "www"
from = request.subdomain.downcase #+ "." + request.domain.downcase
puts from
@license = cache_license(ENV["SX_PROVISION_URL"], from) # request.subdomain.downcase
if (!@license.nil?)
# logger.info "Location - " + @license.name
ActiveRecord::Base.establish_connection(website_connection(@license))
@@ -54,10 +57,18 @@ class ApplicationController < ActionController::Base
end
def cache_license(url, lookup)
@license = License.new(url, lookup)
# Export for Key
aes = MyAesCrypt.new
aes_key, aes_iv = aes.export_key(lookup)
flag = ENV["AES_IV"]
@license = License.new(url, lookup)
# Check Exists IV
if flag == "<%= ENV['AES_IV'] %>"
# Export for Key
aes = MyAesCrypt.new
aes_key, aes_iv = aes.export_key(lookup)
else
aes_key = ENV["AES_KEY"]
aes_iv = ENV["AES_IV"]
end
if (@license.detail_with_local_cache(lookup, aes_key, aes_iv) == true)
return @license
@@ -110,7 +121,7 @@ class ApplicationController < ActionController::Base
if License.check_license_file
return true
else
redirect_to install_path
redirect_to activate_path
end
end
end

View File

@@ -1,42 +1,77 @@
class InstallController < BaseController
skip_before_action :verify_authenticity_token
before_action :check_license
def index
end
def create
def activate
flag = "<%= ENV['AES_IV'] %>"
key_base = "<%= ENV['secret_key_base'] %>"
restaurant = params[:restaurant_name]
license_key = params[:license_key]
admin_user = params[:admin_user]
admin_password = params[:admin_password]
# admin_user = params[:admin_user]
# admin_password = params[:admin_password]
db_host = params[:db_host]
db_schema = params[:db_schema]
db_user = params[:db_user]
db_password = params[:db_password]
phrase = key_base == "<%= ENV['secret_key_base'] %>"? license_key : "<%= ENV['secret_key_base'] %>"
# Check Exists IV
if flag == "<%= ENV['AES_IV'] %>"
# Export for Key
aes = MyAesCrypt.new
aes_key, aes_iv = aes.export_key(phrase)
else
aes_key = ENV["AES_KEY"]
aes_iv = ENV["AES_IV"]
end
@license = License.new(ENV["SX_PROVISION_URL"])
response = @license.license_activate(aes_key, aes_iv, license_key, db_host, db_schema, db_user, db_password)
if response[:status]
redirect_to root_url, notice: response["message"]
else
redirect_to activate_path, notice: response["message"]
end
end
def lookup_domain
if request.subdomain.present? && request.subdomain != "www"
@license = current_license(ENV["SX_PROVISION_URL"], request.subdomain.downcase)
if (!@license.nil?)
# logger.info "Location - " + @license.name
ActiveRecord::Base.establish_connection(website_connection(@license))
# logger.info "Connecting to - " + @license.subdomain + " - "+ @license.dbhost + "@" + @license.dbschema
else
# reconnect_default_db
logger.info 'License is nil'
# redirect_to root_url(:host => request.domain) + "store_error"
render :json => [{ status: false, message: 'Invalid Access!'}]
end
def check_license
if License.check_license_file
redirect_to root_url
end
end
def current_license(url, key)
@license = License.new(url, key)
# def lookup_domain
# if request.subdomain.present? && request.subdomain != "www"
# @license = current_license(ENV["SX_PROVISION_URL"], request.subdomain.downcase)
# if (!@license.nil?)
# # logger.info "Location - " + @license.name
# ActiveRecord::Base.establish_connection(website_connection(@license))
# # logger.info "Connecting to - " + @license.subdomain + " - "+ @license.dbhost + "@" + @license.dbschema
# else
# # reconnect_default_db
# logger.info 'License is nil'
# # redirect_to root_url(:host => request.domain) + "store_error"
# render :json => [{ status: false, message: 'Invalid Access!'}]
# end
# end
# end
##creating md5 hash
md5_hostname = Digest::MD5.new
md5key = md5_hostname.update(request.host)
if (@license.detail_with_local_cache(key, md5key.to_s) == true)
#if (@license.detail == true)
# def current_license(url, key)
# @license = License.new(url, key)
return @license
else
return nil
end
end
# ##creating md5 hash
# md5_hostname = Digest::MD5.new
# md5key = md5_hostname.update(request.host)
# if (@license.detail_with_local_cache(key, md5key.to_s) == true)
# #if (@license.detail == true)
# return @license
# else
# return nil
# end
# end
end

View File

@@ -21,14 +21,6 @@ class License
# @secret = ENV["aes_key"]
# @params = { query: { device: "SX", token: SECRETS_CONFIG['provision_key'] } }
end
def shop_code
if ( self.subdomain.length > 3)
return self.subdomain[0,3].upcase
else
return self.subdomain.upcase
end
end
def detail_with_local_cache(lookup, key, iv)
@@ -41,9 +33,11 @@ class License
cache_license = nil
##Get redis connection from connection pool
Redis.current do |conn|
cache_license = conn.get(cache_key)
end
redis = Redis.new
cache_license = redis.get(cache_key)
# Redis.current do |conn|
# cache_license = conn.get(cache_key)
# end
Rails.logger.info "Cache key - " + cache_key.to_s
if cache_license.nil?
@@ -54,22 +48,27 @@ class License
@license = response.parsed_response
if (@license["status"] == true)
assign()
Rails.logger.info "License - " + response.parsed_response.to_s
Redis.current do |conn|
##Remote - store the remote response in local redis cache
conn.set(cache_key, Marshal.dump(@license))
##ADD to List to remove later
conn.sadd("License:cache:keys", cache_key)
end
redis = Redis.new
redis.set(cache_key, Marshal.dump(@license))
# redis.sadd("License:cache:keys", cache_key)
# Redis.current do |conn|
# ##Remote - store the remote response in local redis cache
# conn.set(cache_key, Marshal.dump(@license))
# ##ADD to List to remove later
# conn.sadd("License:cache:keys", cache_key)
# end
return true
end
Rails.logger.info 'API License'
else
@license = Marshal.load(cache_license)
assign()
Rails.logger.info 'API License'
return true
end
end
@@ -80,65 +79,35 @@ class License
if has_license
# puts "VERIFIED"
end
end
# if cache_license.nil?
# ##change the d/e key
# @params = { query: { lookup_type: self.server_mode, lookup: lookup, encrypted_key: key, iv_key: iv} }
# License Activation
def license_activate (key, iv, license_key, db_host, db_schema, db_user, db_password)
@params = { query: { lookup_type: self.server_mode, encrypted_key: key, iv_key: iv, license_key: license_key } }
response = self.class.get("/activate", @params)
@activate = response.parsed_response
# response = self.class.get("/request_license", @params)
# @license = response.parsed_response
Rails.logger.debug "License Remote Response - " + response.parsed_response.to_s
# if (@license["status"] == true)
# assign()
# Rails.logger.info "License - " + response.parsed_response.to_s
# Redis.current do |conn|
# ##Remote - store the remote response in local redis cache
# conn.set(cache_key, Marshal.dump(@license))
# ##ADD to List to remove later
# conn.sadd("License:cache:keys", cache_key)
# end
# return true
# end
# Rails.logger.info 'API License'
# else
# @license = Marshal.load(cache_license) if cache_license
# Rails.logger.info 'Cache License'
# if (@license["status"] == true)
# assign()
# return true
# end
# end
# return false
end
def detail
response = self.class.get("/subdomain", @options)
@license = response.parsed_response
Rails.logger.debug "License - " + response.parsed_response.to_s
if (@license["status"] == true)
assign()
return true
end
return false
if (@activate["status"])
response = create_license_file(@activate)
if(response["status"])
sym_path = "/home/yan/symmetric/"
response = create_symmetric_config(sym_path, db_host, db_schema, db_user, db_password)
if(response["status"])
response = run_symmetric(sym_path)
end
end
else
response = { "status": false, "message": "Activation Failed! Please contact code2lab call center!"}
end
return response
end
def verify_license
api_token = read_license("api_token")
@options = { query: {lookup_type: "application", token: api_token} }
response = self.class.get("/verify", @options)
@params = { query: {lookup_type: "application", token: api_token} }
response = self.class.get("/verify", @params)
@varified = response.parsed_response
Rails.logger.debug "License Remote Response - " + response.parsed_response.to_s
@@ -152,37 +121,7 @@ class License
return false
end
def check_remote_license(license_key)
# @options = { query: {device: "cloud", key: license_key, skey: @secret, token: Rails.application.secrets.provision_key} }
@options = { query: {lookup_type: "application", encrypted_key: @secret, token: SECRETS_CONFIG['provision_key']} }
response = self.class.get("/license", @options)
@license = response.parsed_response
Rails.logger.debug "License Remote Response - " + response.parsed_response.to_s
if (@license["status"])
assign()
end
return @license["status"]
end
def verify_by_api_token(api_token)
@options = { query: {device: "SX", api_token: api_token, skey: @secret, token: SECRETS_CONFIG['provision_key']} }
response = self.class.get("/verify", @options)
@license = response.parsed_response
Rails.logger.debug "License Remote Response - " + response.parsed_response.to_s
if (@license["status"])
assign()
end
return @license["status"]
end
#Load License is remove from the cloud license because - this license is must be validated against subdmain instead of license.data from file.
# Check License expired date from PROVISION SERVER
def check_expired(renewal_date)
if (renewal_date < Date.today)
return true
@@ -191,6 +130,7 @@ class License
end
end
# Check License File exists
def self.check_license_file
return File.exist?("config/license.yml")
end
@@ -202,13 +142,156 @@ class License
File.open("config/license.yml").each do |line|
if line.include? (key)
decrypted_line_array = line.split(":")
decrypted_line = AESCrypt.decrypt(decrypted_line_array[1])
decrypted_line = AESCrypt.decrypt_data(decode_str(decrypted_line_array[1]), decode_str(ENV['AES_KEY']), decode_str(ENV['AES_IV']), ENV['CIPHER_TYPE'])
end
end
end
end
private
def decode_str(str)
return Base64.decode64(str)
end
# License File Creation
def create_license_file(response_data)
if File.exist?("config/license.yml")
delete_license_file
end
begin
# Licese File Creation
f = File.open("config/license.yml", "w")
f.write("iv_key: #{response_data['iv_key']}\n")
f.write("shop_name: #{response_data['shop_name']}\n")
f.write("email: #{response_data['email']}\n")
f.write("telephone: #{response_data['telephone']}\n")
f.write("fax: #{response_data['fax']}\n")
f.write("address: #{response_data['address']}\n")
f.write("dbhost: #{response_data['dbhost']}\n")
f.write("dbschema: #{response_data['dbschema']}\n")
f.write("dbusername: #{response_data['dbusername']}\n")
f.write("dbpassword: #{response_data['dbpassword']}\n")
f.write("api_token: #{response_data['api_token']}\n")
f.write("app_token: #{response_data['app_token']}\n")
f.close
rescue IOError
response = { "status": false, "message": "Activation is success but something is wrong. \n Please contact code2lab call center!"}
end
response = { "status": true, "message": "Success Activation. License also created."}
end
# Symmetric Configuration
def create_symmetric_config(sym_location, db_host, db_schema, db_user, db_password)
if File.directory? (sym_location)
begin
# sx properties create
f = File.open(sym_location + "engines/sx.properties", "w")
f.write("engine.name=sx\n")
f.write("db.driver=com.mysql.jdbc.Driver\n")
f.write("db.url=jdbc:mysql://#{db_host}/#{db_schema}?tinyInt1isBit=false\n")
f.write("db.user=#{db_user}\n")
f.write("db.password=#{db_password}\n")
f.write("registration.url=\n")
f.write("sync.url=http://#{db_host}:31415/sync/sx\n")
f.write("group.id=sx\n")
f.write("external.id=000\n")
f.write("job.purge.period.time.ms=7200000\n")
f.write("job.routing.period.time.ms=5000\n")
f.write("job.push.period.time.ms=10000\n")
f.write("job.pull.period.time.ms=10000\n")
f.write("initial.load.create.first=true\n")
f.write("initial.load.use.extract.job.enabled=true\n")
f.close
# read from license file
shop_name = read_license("shop_name")
dbhost = read_license("dbhost")
dbschema = read_license("dbschema")
dbusername = read_license("dbusername")
dbpassword = read_license("dbpassword")
# shop properties create
f = File.open(sym_location + "/#{shop_name}.properties", "w")
f.write("engine.name=#{shop_name}\n")
f.write("db.driver=com.mysql.jdbc.Driver\n")
f.write("db.url=jdbc:mysql://#{dbhost}/#{dbschema}?tinyInt1isBit=false\n")
f.write("db.user=#{dbusername}\n")
f.write("db.password=#{dbpassword}\n")
f.write("registration.url=http://#{db_host}:31415/sync/sx\n")
f.write("group.id=store\n")
f.write("external.id=001\n")
f.write("job.routing.period.time.ms=5000\n")
f.write("job.push.period.time.ms=10000\n")
f.write("job.pull.period.time.ms=10000\n")
# f.write("initial.load.create.first=true\n")
# f.write("initial.load.use.extract.job.enabled=true\n")
f.close
rescue IOError
response = { "status": false, "message": "Activation is success but something is wrong. \n Please contact code2lab call center!"}
end
response = { "status": true, "message": "Success Activation. License also created."}
end
end
# Run Symmetric
def run_symmetric(sym_path)
check_sym_proc_str = `#{sym_path + "bin/sym_service status"}`
check_sym_proc_str = check_sym_proc_str.split("\n")
sym_install_status = check_sym_proc_str[0].split(": ")
# sym_run_status = check_sym_proc_str[1].split(": ")
# Check Sym Installed
if sym_install_status[1] == "false"
response = { "status": false, "message": "Activation is success but Symmetric service not Installed. \n Please contact code2lab call center!"}
end
# Run Sym Service
sym_run_status = check_sym_running(check_sym_proc_str[1], sym_path)
if sym_run_status
# Create Sym Table
check_sym_table = system(sym_path + "bin/symadmin --engine sx create-sym-tables")
if check_sym_table
sym_sql = Rails.root + "db/sym_master.sql"
if File.exist? (sym_sql)
# Import Sym Sql to db and start sym
run_sym_sql = system(sym_path + "bin/dbimport --engine sx " + sym_sql)
run_sym = system(sym_path + "bin/sym")
if run_sym
response = { "status": true, "message": "Activation is success and Configuration done..."}
end
else
response = { "status": false, "message": "Activation is success but Symmetric Sql not Found. \n Please contact code2lab call center!"}
end
end
end
end
# Check Symmetric Running
def check_sym_running(status, sym_path)
# Run Sym Service
if status.include? "Server is already running"
return true
elsif status.include? "false"
sym_start_str = `#{sym_path + "bin/sym_service start"}`
if sym_start_str.include? "Started"
return true
else
check_sym_running(sym_start_status[0])
end
else
return true
end
end
# Delete License File
def delete_license_file
File.delete("config/license.yml") if File.exist?("config/license.yml")
end
# Assign db info for Cloud
def assign
# self.name = @license["name"]
# self.address_1 = @license["address_1"]
@@ -228,17 +311,24 @@ class License
## self.plan_activation_date = Date.strptime(@license["plan_activation_date"], "%Y-%m-%d")
## self.plan_next_renewal_date = Date.strptime(@license["plan_next_renewal_date"], "%Y-%m-%d")
# self.plan_max_products = @license["plan_max_products"].to_i
# self.plan_max_customers = @license["plan_max_customers"].to_i
# self.plan_active_connections = @license["plan_active_connections"].to_i
salt = @license["secret_key"]
# salt = @license["secret_key"]
if (@license["dbhost"] || @license["dbschema"] || @license["dbusername"] || @license["dbpassword"] )
self.dbhost = AESCrypt.decrypt(@license["dbhost"], salt)
self.dbschema = AESCrypt.decrypt(@license["dbschema"], salt)
self.dbusername = AESCrypt.decrypt(@license["dbusername"], salt)
self.dbpassword = AESCrypt.decrypt(@license["dbpassword"], salt)
key = Base64.decode64(ENV['AES_KEY'])
iv = Base64.decode64(ENV['AES_IV'])
if (@license["dbhost"] || @license["dbschema"] || @license["dbusername"] || @license["dbpassword"] )
host = Base64.decode64(@license["dbhost"])
dbschema = Base64.decode64(@license["dbschema"])
dbusername = Base64.decode64(@license["dbusername"])
dbpassword = Base64.decode64(@license["dbpassword"])
self.dbhost = AESCrypt.decrypt_data(host, key, iv, ENV['CIPHER_TYPE'])
self.dbschema = AESCrypt.decrypt_data(dbschema, key, iv, ENV['CIPHER_TYPE'])
self.dbusername = AESCrypt.decrypt_data(dbusername, key, iv, ENV['CIPHER_TYPE'])
self.dbpassword = AESCrypt.decrypt_data(dbpassword, key, iv, ENV['CIPHER_TYPE'])
end
# self.exchange_unqiue_id = @license["exchange_unqiue_id"]

View File

@@ -1,3 +1,6 @@
require 'openssl'
require 'base64'
class MyAesCrypt
@cipher = ""
@@ -7,11 +10,16 @@ class MyAesCrypt
def export_key(passphrase)
# We want a 256 bit key symetric key based on passphrase
# for cloud is lookup
# for local is license_key
# iv_salt = passphrase+"c2l"
digest = Digest::SHA256.new
key = digest.update(passphrase)
key = digest.digest
ENV['AES_KEY'] = cipher_key = key # stores the key in key, and also sets the generated key on the @cipher
ENV['AES_IV'] = cipher_iv = @cipher.random_iv # stores the iv in iv, and also sets the generated iv on the @cipher
key_digest = digest.update(passphrase)
# iv_digest = digest.update(iv_salt)
key = key_digest.digest
# iv = iv_digest.digest
ENV['AES_KEY'] = cipher_key = Base64.encode64(key) # stores the key in key, and also sets the generated key on the @cipher
ENV['AES_IV'] = cipher_iv = Base64.encode64(@cipher.random_iv) # stores the iv in iv, and also sets the generated iv on the @cipher
return cipher_key, cipher_iv
end

View File

@@ -160,6 +160,5 @@ class SaleItem < ApplicationRecord
private
def generate_custom_id
self.sale_item_id = SeedGenerator.generate_id(self.class.name, "SLI")
end
end

View File

@@ -1,4 +1,4 @@
<form action="/install" method="POST" class="row">
<form action="/activate" method="POST" class="row">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Business Name</label>
@@ -10,7 +10,7 @@
<input type="text" class="form-control" name="license_key" aria-describedby="license_key" placeholder="Add License Key">
<small class="form-text text-muted">Add License Key from Email</small>
</div>
<div class="form-group">
<!-- <div class="form-group">
<label for="lblAdministrator">Administrator Username</label>
<input type="text" class="form-control" name="admin_user" aria-describedby="admin_user" placeholder="Administrator Username">
<small id="admin_user" class="form-text text-muted">First Employee who will be assign as administrator</small>
@@ -18,9 +18,17 @@
<div class="form-group">
<label for="admin_password">Password</label>
<input type="password" class="form-control" name="admin_password" placeholder="Password">
</div>
</div> -->
</div>
<div class="col-md-6">
<div class="form-group">
<label for="lblDBHost">Database Host</label>
<input type="text" class="form-control" name="db_host" aria-describedby="db_host" placeholder="Database Host" />
</div>
<div class="form-group">
<label for="lblDBName">Database Schema</label>
<input type="text" class="form-control" name="db_schema" aria-describedby="db_schema" placeholder="Database Schema">
</div>
<div class="form-group">
<label for="lblAdministrator">Database Username</label>
<input type="text" class="form-control" name="db_user" aria-describedby="db_user" placeholder="Database Username">

View File

@@ -70,7 +70,7 @@
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 p-t-20 p-l-10 p-r-10 p-b-50 bg-white">
<div class="row justify-content-center form-group">
<!-- <span class="col-md-4"></span> -->
<input type="text" class="form-control col-4" id="emp_id" onkeypress="empID()" placeholder="Access PIN">
<input type="text" class="form-control col-4" id="emp_id" onkeypress="empID()" placeholder="Employee ID">
<!-- <span class="col-md-4"></span> -->
</div>