Hash parameters to validate request
Hashes are equal if strings are equal.
That is, the aspect of that JSON is a bad choice for hashing is true: Semantically identical JSON objects can have different string representations.
On the Internet, you should, however, expect that also string representations can be complicated depending on the locale of both involved computers. If the locale is equal, everything is usually fine (choose UTF-8 everywhere is valid). However, I expect PHP to convert strings to the locale of the server. This can change the bit-representation of the string (similar to the JSON issue). Therefore, make sure that both work in the same locale and that such magic can never interefere with your system.
Better way to validates a hash parameter in a method on Ruby?
Use Hash#fetch
:
def foo_method(config)
foo = config.fetch(:foo)
bar = config.fetch(:bar)
qux = config.fetch(:qux, {})
end
foo_method({}) #=> key not found: :foo (KeyError)
foo_method({foo: 1}) #=> key not found: :bar (KeyError)
foo_method({foo: 1, bar: 2}) #=> no error
You can also pass a block to fetch
that is called if they given key was not found, e.g.: foo = config.fetch(:foo) { raise ArgumentError, "No foo config found" }
Writing validations for an array of hashes parameter in rails
You can write a simple custom validation method yourself. Something like this might be a good start:
validate :format_of_books_array
def format_of_books_array
unless books.is_a?(Array) && books.all? { |b| b.is_a?(Hash) }
errors.add(:books, "is not an array of hashes")
return
end
errors.add(:books, "not all bookIds are integers") unless books.all? { |b| b[:bookId].is_a?(Integer) }
errors.add(:books, "includes invalid genres") unless books.all? { |b| b[:genre].in?(%w[crime romance thriller fantasy]) }
errors.add(:books, "includes invalid author array") unless books.all? { |b| b[:authors].is_a?(Array) && b[:authors].all? { |a| a.is_a?(Integer) } }
end
How to validate request with hashed value for exist on table column?
You can use thecheck
method of the Hash facade, from the docs:Now, you can use this in a Custom Validation Rule:use Illuminate\Support\Facades\Hash;
// some code
if (Hash::check('plain-text', $hashedElement)) {
// The elements match...
}
1. Creating Rule class
php artisan make:rule HashedNameCheck
2. Customize class
app\Rules\HashedNameCheck.php<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Hash; // <-- notice.
class HashedNameCheck implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
// here you get the hashed name stored in your database (?)
$hashedName = App\User::find(1)->name;
// next, you compare this with the received value.
return Hash::check($value, $hashedName);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The :attribute does not match with the stored value.';
}
}
3. Apply the rule.
Use this in your controller:$request->validate([
// some other validation rules..
'name' => ['required', 'unique:users', new HashedNameCheck],
]);
or in your custom Form Request class:public function rules()
{
return [
// some other validation rules..
'name' => ['required','unique:users', new HashedNameCheck],
];
}
How to validate Parameters against a long set in PowerShell?
Ansgar Wiechers rightly points out that in your case you need to perform the argument validation inside your script, given that the values to validate against aren't yet available at script declaration (parsing) time; using a script block (for simplicity) to demonstrate the technique:
& {
param(
[string] $SomeParam
)
# The hashtable to validate against.
$hashTable = @{ foo = 1; bar = 2; baz = 3 }
# Check the -SomeParam argument against the keys of $hashTable.
if (-not $hashTable.ContainsKey($SomeParam)) {
Throw "Invalid -SomeParam argument: $SomeParam"
}
# ...
} bar # OK, because 'bar' is a key in $hashTable
Flow of validating a user with hashed password?
It looks like you may be thinking of it backwards. The salt is added to the cleartext password before passing to the hash function. Store the end result in the database.
Commonly, the salt is the username. Something unique to each user to thwart dictionary attacks. (A dictionary attack relies on the economy of scale by cracking one password and then looking for other instances of the same crypto-text. It used to work especially well on very large user databases like well known sites that have millions of users, but hopefully those sites use proper salting and key derivation nowadays).
So for username u, password p, assume SHA2 is hash function. Concatenate u + p to get a salted value, then hash it.
hashtext = SHA2(u + p) // in this case, + is concatenate
hashtext is what you store in the database.For the login, user enters his username u2 and password p2:
tryhash = SHA2(u2 + p2)
Query database for a user record matching u2, with password hashtext of tryhashLets say you have an MVC action receiving loginViewModel which is populated with cleartext email or username as well as cleartext password, entered from the page:
var loginUser = new User(loginViewModel);
CalcHash(loginUser);
var realUser = users.Find(loginUser.username);
if(realUser.HashPassword == loginUser.HashPassword)
// success
While it is also possible to add the hashed password as a second argument to your Data Access method, ie. users.Find(username, hashPass)
, it is usually not done this way, because you need to access the user record even if the password fails, in order to increment password failure count and lockout the account.
Related Topics
After_Save Callback to Set The Updated_By Column to The Current_User
How to Test Helpers Blocks in Sinatra, Using Rspec
Get Value from String Representing Local Variable
How to Fix a Deadlock in Join() in Ruby
How Can Multiple Trailing Slashes Can Be Removed from a Url in Ruby
How to Access Sinatra App on Host Machine with Vagrant Forwarded Ports
How to Use Strong Parameters with an Objects Array in Rails
How to Remove Header and Footer from Some of The Pages in Ruby on Rails
One or More Params in Model Find Conditions with Ruby on Rails
Sqlite3::Sqlexception: Duplicate Column Name While Migrating
How to Downgrade My Rails Version
How to Display Image Pointed by Url in Rails
What Is The Ruby Equivalent to This Curl Request
Difference Between @@ and @ in Ruby
How to Convert a Fraction to Float in Ruby