Laravel Auth::user() get attributes - authentication

when i dump( Auth::user()); that show me
User {#220 ▼
#attributes: array:10 [▼
"id" => "8"
"name" => "Vitaliy"
"email" => "dsadsa#i.ua"
"password" => "=)"
"remember_token" => null
"created_at" => "2017-10-19 13:11:21"
"updated_at" => "2017-10-19 13:11:21"
"phone" => "412412412"
"city" => "Dnipro"
"district" => "Leneinskiy"
]
#original: array:10 [▶]
....
}
In protected property we saw the info from user table
How can i get #attributes?
Or say me please how i can take all info about logged User.

Auth::user()->name
Auth::user()->email
etc...

Auth::User()->getAttributes();
This will get all the attributes of the logged in user.

simply you can use
$user = (Auth::User())->toArray();
or
use Illuminate\Support\Collection
$user = (new Collection(Auth::User()))->toArray();

Related

How to allow my user to use their own external SMTP in Yii2

I have an app where I want my user to be able to add their own SMTP server, whether by Mailgun, Amazon SES, etc.
If we're taking the mailgun as an example, right now my Mailgun is set up in config/web.php like so
'mailgun' => [
'class' => 'boundstate\mailgun\Mailer',
'key' => 'MYKEY',
'domain' => 'DOMAIN',
],
Then I use the following to compose an email
Yii::$app->mailgun->compose()->setFrom($FROM)
->setReplyTo($contest_creator_email)
->setTo($email)
->setSubject($subject_line)
->setTextBody($plaintext)
->setHtmlBody($htmlemail)
->send();
How would I make it so that my user could set-up his own key instead of using mine? Is there a way to do this?
You can do this by setting mailer configuration.
Before sending email you can set mailer configuration in your api/controller.
//Set config value dynamicaly
Yii::$app->set('mailer', [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'YourHostName',
'username' => 'UserName',
'password' => 'Password',
'port' => 'Port',
'encryption' => 'Encryption'
],
]);
And send mail as below.
Yii::$app->mailer->compose()->setFrom($FROM)
->setReplyTo($contest_creator_email)
->setTo($email)
->setSubject($subject_line)
->setTextBody($plaintext)
->setHtmlBody($htmlemail)
->send();

Rails 3 execute custom sql query without a model

I need to write a standalone ruby script that is supposed to deal with database. I used code given below in rails 3
#connection = ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => "localhost",
:database => "siteconfig_development",
:username => "root",
:password => "root123"
)
results = #connection.execute("select * from users")
results.each do |row|
puts row[0]
end
but getting error:-
`<main>': undefined method `execute' for #<ActiveRecord::ConnectionAdapters::ConnectionPool:0x00000002867548> (NoMethodError)
what i am missing here?
SOLUTION
After getting solution from denis-bu i used it following way and that worked too.
#connection = ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => "localhost",
:database => "siteconfig_development",
:username => "root",
:password => "root123"
)
sql = "SELECT * from users"
#result = #connection.connection.execute(sql);
#result.each(:as => :hash) do |row|
puts row["email"]
end
Maybe try this:
ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)
connection = ActiveRecord::Base.connection
connection.execute("SQL query")
I'd recommend using ActiveRecord::Base.connection.exec_query instead of ActiveRecord::Base.connection.execute which returns a ActiveRecord::Result (available in rails 3.1+) which is a bit easier to work with.
Then you can access it in various the result in various ways like .rows, .each, or .to_hash
From the docs:
result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>
# Get the column names of the result:
result.columns
# => ["id", "title", "body"]
# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
[2, "title_2", "body_2"],
...
]
# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
{"id" => 2, "title" => "title_2", "body" => "body_2"},
...
]
# ActiveRecord::Result also includes Enumerable.
result.each do |row|
puts row['title'] + " " + row['body']
end
note: copied my answer from here
You could also use find_by_sql
# A simple SQL query spanning multiple tables
Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c #attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
How about this :
#client = TinyTds::Client.new(
:adapter => 'mysql2',
:host => 'host',
:database => 'siteconfig_development',
:username => 'username',
:password => 'password'
sql = "SELECT * FROM users"
result = #client.execute(sql)
results.each do |row|
puts row[0]
end
You need to have TinyTds gem installed, since you didn't specify it in your question I didn't use Active Record

Parse embedded string form JSON

I have a Rails 3 application and I am using the following code to parse a JSON post:
email_payload = JSON.parse(params[:payload])
Result.create(:from => email_payload['from'], :from_name => email_payload['from_name'], :from_address => email_payload['from_address'], :date => email_payload['date'], :html_body => email_payload['html_body'], :priority => email_payload['priority'], :spam_status => email_payload['spam_status'], :subject => email_payload['subject'])
The JSON post data is as follows:
payload{ "address_identifier": null, "attachments": [ [ "twitter.png", "image/png", 3029, "http://api.deliverhq.com/api/incoming/attachment/7gdd71wo75/5772412/0" ] ], "cc": null, "date": "Thu, 25 Oct 2012 22:04:20 +0100"
I am trying to work out how to parse the URL, in this case http://api.deliverhq.com/api/incoming/attachment/7gdd71wo75/5772412/0, and then enter the URL into the database.
:url => email_payload['attachments']
won't work because there is multiple values within attachment and:
email_attachments_payload = JSON.parse(params[:payload][:attachments])
:url => email_attachments_payload['URL']
won't work because the URL doesn't have an identifier. For this particular application there should only ever be one attachment, therefore selecting .first may be an option if that's possible.
Any pointers would be appreciated!
UPDATE:
Adding:
email_payload[:attachments][0][4]
results in the following exception error:
NoMethodError: undefined method []' for nil:NilClass
UPDATE 2
def receive_fax
if request.get?
render :text => "hello"
elsif request.post?
email_payload = JSON.parse(params[:payload])
Fax.create(:from => email_payload['from'], :from_name => email_payload['from_name'], :from_address => email_payload['from_address'], :date => email_payload['date'], :html_body => email_payload['html_body'], :priority => email_payload['priority'], :spam_status => email_payload['spam_status'], :subject => email_payload['subject'], :fax => email_payload[:attachments][0][3])
render :text => "success"
else
render :text => "error"
end
end
In irb:
require 'json'
email_payload = JSON.parse('{ "address_identifier": null, "attachments": [ [ "twitter.png", "image/png", 3029, "http://api.deliverhq.com/api/incoming/attachment/7gdd71wo75/5772412/0" ] ], "cc": null, "date": "Thu, 25 Oct 2012 22:04:20 +0100" }')
#=> {"address_identifier"=>nil, "attachments"=>[["twitter.png", "image/png", 3029, "http://api.deliverhq.com/api/incoming/attachment/7gdd71wo75/5772412/0"]], "cc"=>nil, "date"=>"Thu, 25 Oct 2012 22:04:20 +0100"}
email_payload['attachments'][0][3]
#=> "http://api.deliverhq.com/api/incoming/attachment/7gdd71wo75/5772412/0"
If that doesn't work then there's something else going on that you haven't described above.
UPDATE: in the hash returned from JSON.parse, the attachments key should be a string ('attachments'), not a symbol (:attachments). Updated my answer above.
Please try: email_payload['attachments'][0][3]
It appears that the problem may be the difference between :attachments (a symbol) and 'attachments' (a string).

why am I getting a 'no route matches' error in Rails 3?

I have in my haml:
= link_to("Calls Today", todo_path)
And in my routes.rb:
match "todo/today" => "todo#show_date"
match "todo/today/campaign/:id" => "todo#show_date", :as => "todo"
My understanding is that 'todo_path' should find todo controller and show_date.
This route :
match "todo/today/campaign/:id" => "todo#show_date", :as => "todo"
Expects an id parameter. Therefore, your link_to should be like :
= link_to("Calls Today", todo_path(:id => your_id))

CakePHP Auth Component validation issue

Have some validating problems which seem to appear only when using the Auth component.
I have 4 fields in my register form: username, password, password_confirm and email.
I also have the multivalidatable behaviour attached to my User model. Here are the rules which apply to the register form:
var $validationSets=array(
"register" => array(
"username" => array(
"usernameFieldNotEmpty" => array(
"rule" => "notEmpty",
"message" => "You did not enter the username!"
),
"usernameValid" => array(
"rule" => "__alphaNumericDashUnderscore",
"message" => "The username you entered is not valid!"
),
"usernameExistsInDatabase" => array(
"rule" => array("__existingRecord", false),
"message" => "The username you entered has been already registered in our database!"
)
),
"password" => array(
"passwordFieldNotEmpty" => array(
"rule" => "notEmpty",
"message" => "You did not enter your password!"
)
),
"password_confirm" => array(
"passwordConfirmFieldNotEmpty" => array(
"rule" => "notEmpty",
"message" => "You did not confirm your password!"
),
"passwordsMatch" => array(
"rule" => array("__fieldMatch", "password"),
"message" => "The passwords you entered don't match!"
)
),
"email" => array(
"emailFieldNotEmpty" => array(
"rule" => "notEmpty",
"message" => "You did not enter the e-mail!"
),
"emailValid" => array(
"rule" => "email",
"message" => "The e-mail you entered is not valid!"
),
"emailExistsInDatabase" => array(
"rule" => array("__existingRecord", false),
"message" => "The e-mail you entered has been already registered in our database!"
)
)
/*"language" => array(
)*/
)
Here is my register form:
<?php echo $this->Form->create('User', array('url' => array('controller' => 'users', 'action' => 'register')));?>
<fieldset>
<legend><?php __('Add User'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password', array('type' => 'password', 'value' => ''));//value='' - resets the password input on any error on the page
echo $this->Form->input('password_confirm', array('type' => 'password', 'value' => ''));
echo $this->Form->input('email');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
Now, everytime I submit the form EMPTY, the password field, although empty, passes all validation tests (I tried putting value => '' in the code, but it's useless).
Also, the email input seems to pass the 'notEmpty' test and the error shown is that The email is not valid
I've looked over all my code but couldn't find any solution.
http://pastebin.com/xnQ02BCW
this is what i would use.
About the Password problem: what version of CakePHP are you using?
The Auth component in 1.2 automatically hash your password, so that it will result not empty even if it is. In 1.3 it should be OK but I don't know from what version.
I've managed to do a couple of "hacks" so the problem is solved for now.
Don't think this is the most appropriate way of doing it, but it might get in handy for other users having my problem:
Firstly, in my UsersController, I wrote this snippet, so if the password field is left empty by the user, reset it to '' before validation:
if($this->data['User']['password'] == $this->Auth->password('')){
$this->data['User']['password'] = '';
}
$this->User->set($this->data);
if($this->User->validates()){ //post validation login }
The second problem was the e-mail validation. Oddly, I got this problem fixed by changing the order of the rules in the Multivalidatable Behaviour. So, from:
"email" => array(
"emailFieldNotEmpty" => array(
"rule" => "notEmpty",
"message" => "You did not enter the e-mail!"
),
"emailValid" => array(
"rule" => "email",
"message" => "The e-mail you entered is not valid!"
),
"emailExistsInDatabase" => array(
"rule" => array("__existingRecord", false),
"message" => "The e-mail you entered has been already registered in our database!"
)
)
I now have:
"email" => array(
"emailExistsInDatabase" => array(
"rule" => array("__existingRecord", false),
"message" => "The e-mail you entered has been already registered in our database!"
),
"emailValid" => array(
"rule" => "email",
"message" => "The e-mail you entered is not valid!"
),
"emailFieldNotEmpty" => array(
"rule" => "notEmpty",
"message" => "You did not enter the e-mail!"
)
)
I don't know whether this was intended or not, but it seems like the last rule which isn't fulfilled is the one displayed. To my logic, the rules would have been arranged in their order of appearance, so if the first one doesn't apply, stop checking and display it.
I repeat, I don't know if this is the right approach, but I seem to have worked out these problems.
If you have anything to add up, please do so!
EDIT
Found the 'official' explanation in the Cake 1.3 Book. It says:
By default CakePHP tries to validate a field using all the validation rules declared for it and returns the error message for the last failing rule. But if the key last is set to true for a rule and it fails, then the error message for that rule is returned and further rules are not validated. So if you prefer to show the error message for the first failing rule then set 'last' => true for each rule.
So, another approach to my problem is to set the validation rules in their order of appearance and add a last key to the rule array.