I just want to know whether i can use include? method in this place or not, Is it appropriate to use include method here?
I have a Users table and a Roles table, there are many_to_many relation in b/w user & role.
Now i want to check the role of the user.
something like this:
1. Using include
This is returning false whereas i am expecting true, coz that user having admin role.
def isadmin(user)
user.roles.include?("admin")
end
2. Without include
This solution is working for me but i want to know about include.
def isadmin(user)
for role in user.roles
if role.name == "admin"
return true
end
end
false
end
Note: I have this role assigned to the user for whom i am checking the role.
#<Role id: 1, name: "admin", created_at: "2014-12-07 07:45:42", updated_at: "2014-12-07 07:45:42">
The first one isn't working because you're comparing an array of role objects to a string. You want something like this:
user.roles.map(&:name).include?('admin')
Related
so I am currently trying to find out if there is a way I could give a user a role by typing the a variable name. Like, example, '!role testrole', and then the bot will give them what the testrole is defined at. Like, 'if(args[1] === "testrole")...'. Testrole can just be defined as that, but the actual role name can just be like test. You can add multiple roles, and it will add it. '!role hello', etc...? Discord.JS
You can try something simple using a function to find the role name. You can do something like:
const roleName = message.guild.roles.cache.find(r => (r.name === args[1].toString()) || (r.id === args[1].toString().replace(/[^\w\s]/gi, '')));
This will either check for a mentioned role or a role name given
I tried updating my firestore security rules to this:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /entries/{entry}{
allow read, create, update, delete, write: if request.auth != null && request.auth.uid == resource.data.user;
//user is a property of every document in my collection which holds the user id of logged user
}
}
}
My issue is that I am able to read, update and delete data but not able to create new documents in this collection..what am i doing wrong?
Edit:
console.log(firebaseApp.auth.currentUser.uid)
firebaseApp.db.collection("entries").add({
content: encrypt(entryContent),
time: entryDate.getTime(),
user: firebaseApp.auth.currentUser.uid,
});
this is the code which is adding new a new doc..
resource.data (in fact, the resource object) represents the database document being accessed. In a create situation, it won't exist yet, so it won't be available to match. For create, you'll need to match on the request object, which represents the state of the document AFTER the transaction.
I strongly suggest you separate your rules into read, create etc individually, which will allow you to see what you are creating more easily.
Further, the documentation suggest you do NOT have overlapping rules of write with create, update, delete - since the former is just shorthand for the latter three.
Your rules require that the existing document data contain a field called "user" to be the same as the user's uid:
request.auth.uid == resource.data.user
resource.data contains the fields of an existing document that's being read or written. Non-existing documents don't have a value for resource.data. So, if you are creating a new document, this will always evaluate false.
If you want to allow arbitrary users to create a new document, you should have a create rule that looks like this:
allow create: if true;
If you want to require that users can only create new document that have a field called "user" with their UID, you should use request.resource to look at the incoming document data before it's created:
allow create: if request.resource.data.user == request.auth.uid;
Is there a way where a user inputs 2 values like 'username' and 'password'. Can I then check the array to see if these elements are present and then grant the user access? If they are granted access it would print out there admin rights: print('admin') or print('user')
Array:
myArray = ['bob', '123', 'admin',
'sam', 'qwerty', 'user']
Thanks in advance!
All you really need to do is check if the user is in your user list and make sure the password matches the username. To do that, dictionaries would be best. This way, you can match the password with the username.
users = {'bob': 'pass', '123': 'pass', 'admin': 'pass',
'sam': 'pass', 'qwerty': 'pass', 'user': 'pass'}
Here you set the users and their passwords into a dictionary, you can preset this or you can have a function to create a new user which will be added to the dictionary. A dictionary basically just associates two key values to each other. Ex: (one: 1, two: 2)
login = input("Enter username: ")
password = input("Enter password: ")
Here you're simply setting the variables login and password to user input.
if login in users and users[login] == password:
print("Login successful!")
else:
print("Login invalid")
Finally, here you're checking to see if what the user inputted is in the dictionary of users and passwords. If whatever the user inputs, whether it be username or password, isn't in the dictionary then they will get the login invalid.
I hope this helped you. There are ways to allow the user to create a new profile, if you want to know how to do that just let me know! If you get stuck or don't understand anything I just said, I will of course verify and answer any questions.
I have a User class as follows:
class User
attr_reader :username, :password
def inintialize(username, password)
#username = username
#password = password
end
end
And I want to store many of these User classes in an array as follows:
users = []
def initialize_users
user = User.new("user0", "password0")
users.push(user)
user = User.new("user1", "password1")
users.push(user)
end
And now I want to implement a searching function where I can search via username, or password. I know I can iterate over the classes comparing each field like so:
def search(username)
users.each do |user|
if user.username == username then
puts "Found"
break
end
end
end
But is there any other way to do this without the iterating or is this simply the easiest/cleanest way?
I was thinking maybe there is a way to do something like:
users["username_to_find"]
=> true
Although I am not sure how to implement that. I would believe I would have to rewrite the User class to have a built in list, but from there I am lost. I guess even if I do implement this feature there is still a iteration that has to happen.
Also I would like to access that users data from within that notation such as
users["username_to_find"].password
=> "password111"
Anyone have any ideas?
PS: User class is reduced to relevant code, it actually holds many more data members which are specific to each user such as sockets, and methods for sending data to a specific users sockets.
You really have no choice but to iterate over every element of the array and perform your matching test. Enumberable#detect is what you would want to use:
def search(username)
# return the first matching result
users.detect { |user| user.username == username }
end
This would return the first User with a matching username or nil. If you want to allow multiple results to be returned (e.g. more of what the word "search" denotes) than you would want to use Enumberable#select which returns all matching blocks:
def search(username)
# return ALL matching results
users.select { |user| user.username == username }
end
If you need to potentially match on multiple criteria (e.g. search on username and first name, etc) than you will need to take this approach. If you are only searching on username, than the solution given by #dax above is perfect.
If it doesn't need to be an Array, why not use a Hash? It provides exactly the functionality you want.
users = {}
user = User.new("user0", "password0")
users[user.username] = user
Access it like so
users['tim_the_toolman'] # => nil, there is no user by that name
users['user0'] # => returns user0
users['user0'].password # => 'password0'
use Array find and select methods. Assume you are searching by name
find returns first object which satisfies your condition
array.find { |user| user.name == searched_name } # will be either one User or nil, if neither has name eq to searched_name
select returns all objects which satisfy your condition
array.select { |user| user.name == searched_name } #will be either array of Users which have name eq searched_name or an empty array when none has this name
I've just started out using MongoDB and, in particular, Mongoid.
naturally I'd like to ensure my User's passwords are kept nice and secure, and previously I'd have done this with ActiveRecord and used bcrypt. I'm looking for a nice, clean, secure, simple way to implement the same sort of thing using Mongoid.
I've taken a look at mongoid-encryptor but I've not quite got my head around how to use it.
Assume my simplified User looks like this, as per the example in mongoid-encryptor's Readme file.
class User
include Mongoid::Document
include Mongoid::Encryptor
field :name
field :password
encrypts :password
end
And in my WebApp (using Sinatra in this case) I'd define a helper such as
def login (name, cleartxtpass)
return User.where(name: name, password: cleartxtpass).first
end
How do I get it to use bcrypt?
Is there any pre-processing I need to do with cleartxtpass or will Mongoid::Encryptor just handle that? It's not clear from the docs.
Okay well after some digging I decided to not bother using Mongoid::Encryptor but to stick to the tried and tested way I used to do these things when using ActiveRecord.
So now my User looks like
class User
include Mongoid::Document
field :name, type: String
field :password_hash, type: String
index({name: 1}, {unique: true, name: 'user_name_index'})
include BCrypt
def password
#password ||= Password.new(password_hash)
end
def password=(new_password)
#password = Password.create(new_password)
self.password_hash = #password
end
end
and my authenticate helper method looks like
def auth_user(username, password)
user = User.where(name: username).first
return user if user && user.password == password
return nil
end
That works a treat.
The simply way to do it is:
class User
include Mongoid::Document
include ActiveModel::SecurePassword
field :name, type: String
field :password_digest, type: String
has_secure_password
end