Find Username and Password Elements In An Array - arrays

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.

Related

How do I get someones username AND tag? (Discord.js)

So, I'm trying to make a serverInfo command as you can see below
let embed = new Discord.MessageEmbed()
.setColor("GREEN")
.setTitle("Server Information")
.setDescription(`Server Name: **${message.guild.name}** \n ────────────────── \n Member Count: **${message.guild.memberCount}** \n ────────────────── \n Server ID: **${message.guild.id}** \n ──────────────────`)
.setTimestamp()
.setFooter(`Ran by: ${message.author.username.id}`)
message.channel.send(embed)
For my result, I get "undefiened"
anyone know the solution to this? (.setFooter)
message.author.tag for get the user with tag (JohnDoe#0000)
message.author.user for get the user
message.author.user.username for get the Username
message.author.user.id for get the ID
Simple (:
To get the complete tag of a user, you can just use .tag after message.author.
In your code, you're trying to get the username but you put .id after it so this is why you get "undefined".
The ID isn't the numbers with the hashtag, it's the user ID and the tag is the username plus the numbers with the hashtag.
⠀⠀⠀↱ John Doe#3040 ↰
Username⠀⠀⠀⠀ ⠀⠀Numbers
↳⠀⠀⠀⠀⠀⠀⠀⠀Tag⠀⠀⠀⠀⠀⠀⠀ ↲
So, to get the username and tag, just do this:
//say it’s called msg instead of message
var tag = msg.author.tag;
var username = msg.author.id;
//tag would return the user's tag, and as someone else stated in a comment in a previous answer, author returns a user, which itself doesn't have a user property because it is the user object
Also just a quick tip: since it’s server info command, you might want to put some information about the user that’s exclusive to that guild (nickname, roles, permissions), and for that, you can use msg.member which returns a GuildMember, which has a user property, and many more, like member.displayName and member.roles

How to implement a search function for array of classes

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

Can we use "include?" in this situation?

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')

How to get or create user profile in GAE?

I have a Profile model:
class Profile(db.Model):
user = db.UserProperty(auto_current_user=True)
bio = db.StringProperty()
I'd like to display the user's existing bio in this view. If the user has no profile yet, I'd like to create it. Here's what I have so far, which doesn't work yet:
class BioPage(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
profile = Profile.get_or_insert(user=user) #This line is wrong
profile.bio = "No bio entered yet."
profile.save()
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, ' + user.nickname() + '<br/>Bio: ' + profile.bio)
else:
self.redirect(users.create_login_url(self.request.uri))
How do I fix the incorrect line above? I know that get_or_insert() should take a key name, but I can't figure out what that would be.
(Should the user field in Profile even be a db.UserProperty?)
You have to pass the key_name to get_or_insert(), in this case, like so:
profile = Profile.get_or_insert(key_name=user.email())
Note that since the user property is auto-populated because of the auto_current_user=True you don't need to pass it to the get_or_insert() call. In your case you don't need to pass anything but the key name.
You probably don't want to use db.UserProperty, for reasons explained here. In summary, if a user changes his/her email address, your (old) stored 'User' will not compare equal to the currently-logged-in (new) 'User'.
Instead, store the user.user_id() as either a StringProperty on your Profile model (as shown on the page I referenced above), or as the key (key_name) of your Profile model. An example of the latter is here.

Converting a User.user_id() to a User.email()

Is there a way to derive a user's email given his user_id?
You can build a relationship between the email and the user_id,and then retrieve it as needed. If the user is logged in you can easily access both properties separately.
http://code.google.com/intl/en/appengine/docs/python/users/userclass.html
However the user_id is not a hashed version of the email that can be reconstructed using some kind of algorithm.
It seems like it's not possible to derive an email from a user id. If you want to go from user_id to email, you must store both when the user is logged in, and then, when the user is not logged in, do a lookup to convert. Eg.
class Email(db.model):
'''keyed by user_id'''
email=db.EmailProperty()
def save_user():
u=users.get_current_user()
k=db.Key.from_path('Email',u.user_id())
e=Email.get(k)
if not e:
Email(key=k, email=u.email()).put()
def get_email_from_user_id(id):
'''No way to derive email without a lookup.'''
k=db.Key.from_path('Email',id)
return Email.get(k).email # raises exception if email is not found

Resources