Skip to content

Instantly share code, notes, and snippets.

@pduersteler
Last active December 24, 2015 07:19
Show Gist options
  • Save pduersteler/6762752 to your computer and use it in GitHub Desktop.
Save pduersteler/6762752 to your computer and use it in GitHub Desktop.
class Credential < ActiveRecord::Base
before_save :encrypt_attributes!
@@key = nil
def self.set_key(key)
@@key = key
end
def self.key_present?
!@@key.nil?
end
def encrypt_attribute(attribute)
return unless @@key
Encryptor.encrypt algorithm: 'blowfish', key: @@key, value: self.send(attribute.to_sym)
end
def decrypt_attribute(attribute)
return unless @@key || self.new_record?
begin
Encryptor.decrypt algorithm: 'blowfish', key: @@key, value: self.send(attribute.to_sym)
rescue OpenSSL::Cipher::CipherError
# Was not encrypted
end
end
private
def encrypt_attributes!
self.host = self.encrypt_attribute(:host) if self.host.present?
self.username = self.encrypt_attribute(:username) if self.username.present?
self.password = self.encrypt_attribute(:password) if self.password.present?
self.description = self.encrypt_attribute(:description) if self.description.present?
end
end
class CredentialsController < ApplicationController
before_filter :assign_encryption_key
before_filter :request_encryption_key, unless: "Credential.key_present?", except: [:set_encryption_key]
def new
@credential = Credential.new
end
def create
@credential = Credential.new credential_params
if @credential.save
redirect_to @credential
else
render action: :new
end
end
private
def request_encryption_key
store_location
render action: 'encryption_key_form'
end
def assign_encryption_key
Credential.set_key session[:encryption_key] if session[:encryption_key].present?
end
def credential_params
params.require(:credential).permit(:name, :host, :username, :password, :description)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment