Class: Visor::Auth::Backends::MySQL

Inherits:
Base
  • Object
show all
Includes:
Common::Exception
Defined in:
lib/auth/backends/mysql_db.rb

Overview

The MySQL Backend for the VISoR Auth.

Constant Summary collapse

DEFAULT_DB =

Connection constants

Default MySQL database

'visor'
DEFAULT_HOST =

Default MySQL host address

'127.0.0.1'
DEFAULT_PORT =

Default MySQL host port

3306
DEFAULT_USER =

Default MySQL user

'visor'
DEFAULT_PASSWORD =

Default MySQL password

'passwd'

Constants inherited from Base

Base::ALL, Base::MANDATORY, Base::READONLY

Instance Attribute Summary

Attributes inherited from Base

#conn, #db, #host, #password, #port, #user

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#set_protected_post, #set_protected_put, #to_sql_insert, #to_sql_update, #to_sql_where, #validate_data_post, #validate_data_put, #validate_query_filters

Constructor Details

#initialize(opts) ⇒ MySQL

Returns a new instance of MySQL.



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/auth/backends/mysql_db.rb', line 56

def initialize(opts)
  super opts
  @conn = connection
  @conn.query %[
CREATE TABLE IF NOT EXISTS `#{opts[:db]}`.`users` (
  `_id` VARCHAR(45) NOT NULL ,
  `access_key` VARCHAR(45) NOT NULL ,
  `secret_key` VARCHAR(45) NOT NULL ,
  `email` VARCHAR(45) NOT NULL ,
  `created_at` DATETIME NULL ,
  `updated_at` DATETIME NULL ,
  PRIMARY KEY (`_id`) )
  ENGINE = InnoDB;
]
end

Class Method Details

.connect(opts = {}) ⇒ Object

Initializes a MongoDB Backend instance.

Parameters:

  • [Hash] (Hash)

    a customizable set of options

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :uri (String)

    The connection uri, if provided, no other option needs to be setted.

  • :db (String) — default: DEFAULT_DB

    The wanted database.

  • :host (String) — default: DEFAULT_HOST

    The host address.

  • :port (Integer) — default: DEFAULT_PORT

    The port to be used.

  • :user (String) — default: DEFAULT_USER

    The user to be used.

  • :password (String) — default: DEFAULT_PASSWORD

    The password to be used.

  • :conn (Object)

    The connection pool to access database.



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/auth/backends/mysql_db.rb', line 44

def self.connect(opts = {})
  opts[:uri]      ||= ''
  uri             = URI.parse(opts[:uri])
  opts[:db]       = uri.path ? uri.path.gsub('/', '') : DEFAULT_DB
  opts[:host]     = uri.host || DEFAULT_HOST
  opts[:port]     = uri.port || DEFAULT_PORT
  opts[:user]     = uri.user || DEFAULT_USER
  opts[:password] = uri.password || DEFAULT_PASSWORD

  self.new opts
end

Instance Method Details

#connectionMysql2::Client

Establishes and returns a MySQL database connection and creates Images table if it does not exists.

Returns:

  • (Mysql2::Client)

    It returns a database client object.



77
78
79
80
# File 'lib/auth/backends/mysql_db.rb', line 77

def connection
  Mysql2::Client.new(host:     @host, port: @port, database: @db,
                     username: @user, password: @password)
end

#delete_all!Object

Delete all images records.



132
133
134
# File 'lib/auth/backends/mysql_db.rb', line 132

def delete_all!
  @conn.query "DELETE FROM users"
end

#delete_user(access_key) ⇒ hash

Delete a registered user.

Parameters:

  • access_key (String)

    The user access_key.

Returns:

  • (hash)

    The deleted image metadata.

Raises:

  • (NotFound)

    If user was not found.



123
124
125
126
127
128
# File 'lib/auth/backends/mysql_db.rb', line 123

def delete_user(access_key)
  user = @conn.query("SELECT * FROM users WHERE access_key='#{access_key}'", symbolize_keys: true).first
  raise NotFound, "No user found with access_key '#{access_key}'." unless user
  @conn.query "DELETE FROM users WHERE access_key='#{access_key}'"
  user
end

#get_user(access_key) ⇒ Hash

Returns an user information.

Parameters:

  • access_key (String)

    The user access_key.

Returns:

  • (Hash)

    The requested user information.

Raises:

  • (NotFound)

    If user was not found.



109
110
111
112
113
# File 'lib/auth/backends/mysql_db.rb', line 109

def get_user(access_key)
  user = @conn.query("SELECT * FROM users WHERE access_key='#{access_key}'", symbolize_keys: true).first
  raise NotFound, "No user found with access_key '#{access_key}'." unless user
  user
end

#get_users(filters = {}) ⇒ Array

Returns an array with the registered users.

Parameters:

  • [Hash] (Hash)

    a customizable set of options

Returns:

  • (Array)

    The users information.

Raises:

  • (NotFound)

    If there are no registered users.



92
93
94
95
96
97
98
99
# File 'lib/auth/backends/mysql_db.rb', line 92

def get_users(filters = {})
  validate_query_filters filters unless filters.empty?
  filter = filters.empty? ? 1 : to_sql_where(filters)
  users = @conn.query("SELECT * FROM users WHERE #{filter}", symbolize_keys: true).to_a
  raise NotFound, "No users found." if users.empty? && filters.empty?
  raise NotFound, "No users found with given parameters." if users.empty?
  users
end

#post_user(user) ⇒ Hash

Create a new user record for the given information.

Parameters:

  • user (Hash)

    The user information.

Returns:

  • (Hash)

    The already added user information.

Raises:

  • (Invalid)

    If user information validation fails.

  • (ConflictError)

    If an access_key was already taken.



145
146
147
148
149
150
151
152
153
154
# File 'lib/auth/backends/mysql_db.rb', line 145

def post_user(user)
  validate_data_post user
  exists = @conn.query("SELECT * FROM users WHERE access_key='#{user[:access_key]}'", symbolize_keys: true).first
  raise ConflictError, "The access_key '#{user[:access_key]}' was already taken." if exists

  set_protected_post user
  keys_values = to_sql_insert(user)
  @conn.query "INSERT INTO users #{keys_values[0]} VALUES #{keys_values[1]}"
  self.get_user(user[:access_key])
end

#put_user(access_key, update) ⇒ BSON::OrderedHash

Update an user information.

Parameters:

  • access_key (String)

    The user access_key.

  • update (Hash)

    The user information update.

Returns:

  • (BSON::OrderedHash)

    The updated user information.

Raises:

  • (Invalid)

    If user information validation fails.

  • (ConflictError)

    If an access_key was already taken.

  • (NotFound)

    If user was not found.



167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/auth/backends/mysql_db.rb', line 167

def put_user(access_key, update)
  validate_data_put update
  user = @conn.query("SELECT * FROM users WHERE access_key='#{access_key}'", symbolize_keys: true).first
  raise NotFound, "No user found with access_key '#{access_key}'." unless user

  if update[:access_key]
    exists = @conn.query("SELECT * FROM users WHERE access_key='#{update[:access_key]}'", symbolize_keys: true).first
    raise ConflictError, "The access_key '#{update[:access_key]}' was already taken." if exists
  end

  set_protected_put update
  @conn.query "UPDATE users SET #{to_sql_update(update)} WHERE access_key='#{access_key}'"
  self.get_user(update[:access_key] || access_key)
end