Laravel 5.1 Auth to get back the username in session? - laravel-5.1

I'm using laravel 5.1, there's method "Auth" can generate the login, register,etc...
But I have a question that how to get "that" username back as I wanted?
For example, I registered as,
email: 123#123.com , name: 123
And in database, I have another table profile, laravel model : Profile, which contains:
email: 123#123.com , sex: male
In here, I want to show "male" in the view.
How laravel work to find specify data across different table ?
Does Laravel has other "word" to represent "this(123#123.com)" when it was logged already (Auth) ?
Thanks!!

Try using this code in your blade view to print sex.
{{ Auth::user()->sex; }}
And using this code to print email
{{ Auth::user()->email; }}
Hope this code works well.

Related

Create user with encrypted password with db:seed

I'm making my first app with rails and this app would be accessible only if user are logged and only admin can create user, so when my app would be online I need at least one admin to create the other right ?
I tried with seed to create an user, the user is well created but I can't connect to my app with it, I think it's a prob with the encrypted password, here is what I have done :
UserManager::User.create({ name: 'a', surname: 'a', email: 'a', active: true, id: 1, password_hash: 'a', password_salt: 'a'})
Is that possible and it is right to create user with seed ? and if it is how can I do to encrypt the password in seed ?
I'm making my first app with rails and this app would be accessible only if user are logged and only admin can create user, so when my app would be online I need at least one admin to create the other right ? Yes
Is that possible and it is right to create user with seed ? This is probably a debatable point, but as long as you secure your seed file, it may be a reasonable approach. You probably want to change the password as soon as possible and/or use an environment variable for your password. Whatever you do, don't use plaintext, add your admin password to your git repository and then leave it unchanged in production.
and if it is how can I do to encrypt the password in seed ? You probably shouldn't be loading attributes like password_hash and password_salt explicitly. Instead, just set password (and password_confirmation if you have it).
You should be Running:
UserManager::User.create(name: 'a', surname: 'a', email: 'a', password: 'foobar123', password_confirmation: 'foobar123')
Other answer by Steve answers the remaining issues.

Rails cookies with chinese characters causes wrong string

I develop app with rails 4 + and angular 1.2.14. When I try to save a chinese username to cookie. And I read it via angularjs $cookieStore. I get a strange string which is unreadable, basically, I think it's the problem of cookie itself can't directly save chinese chracters. But I can't find a proper way to solve it. Even I use string.force_encoding('UTF-8'), nothing happened. Below it the core code about this question.
This is what I store cookie data in ruby controller file:
cookies[:user] = user_info(user)
user_info method is defined as follows:
def user_info(user)
{
id: user.id.to_s,
username: user.username,
role: user.role,
expires: 1.hour.from_now
}.to_json
end
And I get it in angular services with $cookieStore injected before:
_current_user = $cookieStore.get('user')
when I watch this _current_user, the english characters like field id and role are right. But the username I get is a strange string é¾é­.
Is the problem caused by cookie save chinese characters itself, or just caused by angular?
It troubles me a few hours. Thank for those who answer it.

Handling user registration in an Ember.js/Rails/Devise app

I'm playing around with writing a pure Ember.js app on top of Rails 4 and I'm puzzled how user management is handled. My original idea was to use pure server-rendered templates (ERB) to do the user registration and login via Devise, and then the rest of the app would use the Ember framework.
The problem with that is that Ember wants to take over the <body> tag and control the entire viewport. In this way I can't pick and choose which aspects of the app should use server-rendered Erb templates and which should live in the Ember logic.
I see plenty of examples of how to deal with a user that's already logged-in and ember-auth looks interesting to facilitate authentication-aware controllers, but I've seen no tutorials or suggestions on allowing the full user signup experience to take place in the Ember app.
Am I missing something, either from a technical perspective where I just haven't found the right code or from a architectural perspective where I shouldn't be doing it this way?
This is with ember-rails (0.12.0 w/1.0.0.rc3.3 ember-source), Rails 4.0.0.rc1, and Devise (rails4 branch).
ember-auth dev here.
You don't actually need any special treatment for user sign up. Treat user sign up as you would for another model, in the sense that creating a user model will not require authentication. (Editing it or deleting it should require authentication though.)
Your implementation might look like:
App.User = DS.Model.extend
email: DS.attr 'string'
password: DS.attr 'string'
App.UsersNewRoute = Em.Route.extend
model: ->
App.User.createRecord()
App.UsersNewController = Em.ObjectController.extend
create: ->
#store.commit()
Error-checking, template code, etc, skipped for brevity.
This is here for reference to what worked based off of #heartsentwined's answer since pasting in comments doesn't work very well. See the comments for more info. Since my api returns the user json I just pass in the format its expecting.
didCreate: function() {
var user = App.Auth.get('_response').response.user;
var auth = {auth_token: user.auth_token, id: user.id};
App.Auth.get('_response').canonicalize(auth);
App.Auth.trigger('signInSuccess');
}
UPDATE:
I switched to ember-model and now do this in the same place that I call model.save() (the submit action of SignupController).
var model = this.get('model');
model.on('didCreateRecord', function() {
var user = this.data;
var auth = {auth_token: user.auth_token, user_id: user.id, remember_token: user.remember_token};
App.Auth.get('_response').canonicalize(auth);
App.Auth.trigger('signInSuccess');
});
model.save();
The solutions above ALMOST but not quite worked for me. Here is what did work:
didCreate: function() {
var user = App.Auth.get('_response').response.user;
App.Auth.signIn({
data: {
'email': user.email,
'password': this.get('password'),
'remember': true
}
});
}
App.Auth.signIn is used in the documentation explicitly: http://ember-auth.herokuapp.com/docs

Rails log in form case-sensitivity

How would I make a log in form case-insensitive? An example would be a user who signs up with the username "Ralph" can log in after registering using either "Ralph" or "ralph", but store the username as "Ralph" for use with things like friendly_id and views?
It'd be nice if there was a way to do this that wasn't database specific, but implemented in ruby.
Store the username however they give it to you, but call downcase on the string before passing it into whatever method you are authenticating with.

LDAP through Ruby or Rails

I've been attempting to hook a Rails application up to ActiveDirectory. I'll be synchronizing data about users between AD and a database, currently MySQL (but may turn into SQL Server or PostgreSQL).
I've checked out activedirectory-ruby, and it looks really buggy (for a 1.0 release!?). It wraps Net::LDAP, so I tried using that instead, but it's really close to the actual syntax of LDAP, and I enjoyed the abstraction of ActiveDirectory-Ruby because of its ActiveRecord-like syntax.
Is there an elegant ORM-type tool for a directory server? Better yet, if there were some kind of scaffolding tool for LDAP (CRUD for users, groups, organizational units, and so on). Then I could quickly integrate that with my existing authentication code though Authlogic, and keep all of the data synchronized.
Here is sample code I use with the net-ldap gem to verify user logins from the ActiveDirectory server at my work:
require 'net/ldap' # gem install net-ldap
def name_for_login( email, password )
email = email[/\A\w+/].downcase # Throw out the domain, if it was there
email << "#mycompany.com" # I only check people in my company
ldap = Net::LDAP.new(
host: 'ldap.mycompany.com', # Thankfully this is a standard name
auth: { method: :simple, email: email, password:password }
)
if ldap.bind
# Yay, the login credentials were valid!
# Get the user's full name and return it
ldap.search(
base: "OU=Users,OU=Accounts,DC=mycompany,DC=com",
filter: Net::LDAP::Filter.eq( "mail", email ),
attributes: %w[ displayName ],
return_result:true
).first.displayName.first
end
end
The first.displayName.first code at the end looks a little goofy, and so might benefit from some explanation:
Net::LDAP#search always returns an array of results, even if you end up matching only one entry. The first call to first finds the first (and presumably only) entry that matched the email address.
The Net::LDAP::Entry returned by the search conveniently lets you access attributes via method name, so some_entry.displayName is the same as some_entry['displayName'].
Every attribute in a Net::LDAP::Entry is always an array of values, even when only one value is present. Although it might be silly to have a user with multiple "displayName" values, LDAP's generic nature means that it's possible. The final first invocation turns the array-of-one-string into just the string for the user's full name.
Have you tried looking at these:
http://saush.wordpress.com/2006/07/18/rubyrails-user-authentication-with-microsoft-active-directory/
http://xaop.com/blog/2008/06/17/simple-windows-active-directory-ldap-authentication-with-rails/
This is more anecdotal than a real answer...
I had a similar experience using Samba and OpenLDAP server. I couldn't find a library to really do what I wanted so I rolled my own helper classes.
I used ldapbrowser to see what fields Samba filled in when I created a user the "official" way and and basically duplicated that.
The only tricky/non-standard LDAP thing was the crazy password encryption we have:
userPass:
"{MD5}" + Base64.encode64(Digest::MD5.digest(pass))
sambaNTPassword:
OpenSSL::Digest::MD4.hexdigest(Iconv.iconv("UCS-2", "UTF-8", pass).join).upcase
For the def authenticate(user, pass) function I try to get LDAP to bind to the domain using their credentials, if I catch an exception then the login failed, otherwise let them in.
Sorry, cannot comment yet... perhaps someone can relocate this appropriately.
#Phrogz's solution works well, but bind_simple (inside bind) raises an Net::LDAP::LdapError exception due to auth[:username] not being set as shown here:
https://github.com/ruby-ldap/ruby-net-ldap/blob/master/lib/net/ldap.rb
The corrected replaces:
auth: { method: :simple, email: email, password:password }
with:
auth: { method: :simple, username: email, password:password }
I began using ruby-activedirectory, and even extended it/fixed a few things, hosting judy-activedirectory in Github.
Doing the next iteration, I've discovered ActiveLdap has a much better code base, and I'm seriously contemplating switching to it. Does anyone have personal experience with this?
Have you checked out thoughtbot's ldap-activerecord-gateway? It might be something for you to consider...
http://github.com/thoughtbot/ldap-activerecord-gateway/tree/master

Resources