AngularJS - Get Authenticated User Data - angularjs

I'm trying to get the authenticated user data so I can display the name of the user. I'm using AngularJS and Laravel.
When I do:
public function getUser(){
if(Auth::check()){
$user = Auth::user();
$token = JWTAuth::fromUser($user);
dd($user);
return response()->success(compact('user','token'));
}
}
The Auth is null, but I'm logged in.
This is my login method
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:8',
]);
$credentials = $request->only('email', 'password');
try {
// verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->error('Invalid credentials', 401);
}
} catch (\JWTException $e) {
return response()->error('Could not create token', 500);
}
$user = Auth::user();
return response()->success(compact('user', 'token'));
}
Thanks !

Related

Cannot instantiate abstract class Cake\Mailer\Mailer

I want to build forgot password page in cakephp
Here is my code of user controller
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Http\Exception\UnauthorizedException;
use Cake\Mailer\Email;
use Cake\Mailer\Mailer;
use Cake\email\TransportFactory;
use Cake\Auth\DefaultPasswordHasher;
use Cake\Utility\Security;
use Cake\ORM\TableRegistry;
use Cake\Core\InstanceConfigTrait;
/**
Users Controller
#property \App\Model\Table\UsersTable $Users
#method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class UsersController extends AppController {
public function beforeFilter(\Cake\Event\Event $event) {
$this->Auth->allow([‘add’, ‘logout’]);
parent::beforeFilter($event);
}
/**
Index method
#return \Cake\Http\Response|null
*/
public function index() {
if ($this->Auth->user(‘role’) != ‘admin’) {
throw new UnauthorizedException(__(‘You are not allowed to access this page’));
}
$users = $this->paginate($this->Users);
$this->set(compact(‘users’));
}
/**
View method
#param string|null $id User id.
#return \Cake\Http\Response|null
#throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null) {
$user = $this->Users->get($id, [
‘contain’ => [],
]);
$this->set(‘user’, $user);
}
/**
Add method
#return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add() {
if ($this->Auth->user(‘role’) != ‘admin’) {
throw new UnauthorizedException((‘You are not allowed to access this page’));
}
$user = $this->Users->newEntity();
if ($this->request->is(‘post’)) {
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($this->Users->save($user)) {
$this->Flash->success((‘The user has been saved.’));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
$this->set(compact(‘user’));
}
/**
Edit method
#param string|null $id User id.
#return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
#throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null) {
if ($this->Auth->user(‘role’) != ‘admin’) {
throw new UnauthorizedException((‘You are not allowed to access this page’));
}
$user = $this->Users->get($id, [
‘contain’ => [],
]);
if ($this->request->is([‘patch’, ‘post’, ‘put’])) {
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($this->Users->save($user)) {
$this->Flash->success((‘The user has been saved.’));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
$this->set(compact(‘user’));
}
/**
Delete method
#param string|null $id User id.
#return \Cake\Http\Response|null Redirects to index.
#throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null) {
if ($this->Auth->user(‘role’) != ‘admin’) {
throw new UnauthorizedException((‘You are not allowed to access this page’));
}
$this->request->allowMethod([‘post’, ‘delete’]);
$user = $this->Users->get($id);
if ($this->Users->delete($user)) {
$this->Flash->success((‘The user has been deleted.’));
} else {
$this->Flash->error(__(‘The user could not be deleted. Please, try again.’));
}
return $this->redirect([‘action’ => ‘index’]);
}
public function forgotpassword()
{
if ($this->request->is(‘post’)) {
$email = $this->request->getData(‘email’);
$token = Security::hash(Security::randomBytes(25));
$userTable = TableRegistry::get(‘Users’);
if ($email == NULL) {
$this->Flash->error((‘Please insert your email address’));
}
if ($user = $userTable->find(‘all’)->where([‘email’=>$email])->first()) {
$user->token = $token;
if ($userTable->save($user)){
$mailer = new Mailer(‘default’);
$mailer->Transport(‘Smtp’);
$mailer->From([‘noreply[at]codethepixel.com’ => ‘myCake4’])
->setTo($email)
->setEmailFormat(‘html’)
->setSubject(‘Forgot Password Request’)
->deliver(‘Hello
Please click link below to reset your password
Reset Password’);
}
$this->Flash->success(‘Reset password link has been sent to your email (’.$email.’), please check your email’);
}
if ($total = $userTable->find(‘all’)->where([‘email’=>$email])->count()==0) {
$this->Flash->error((‘Email is not registered in system’));
}
}
}
public function resetpassword($token)
{
if($this->request->is(‘post’)){
$hasher = new DefaultPasswordHasher();
$newPass = $hasher->hash($this->request->getData(‘password’));
$userTable = TableRegistry::get(‘Users’);
$user = $userTable->find(‘all’)->where([‘token’=>$token])->first();
$user->password = $newPass;
if ($userTable->save($user)) {
$this->Flash->success(‘Password successfully reset. Please login using your new password’);
return $this->redirect([‘action’=>‘login’]);
}
}
}
public function login() {
if ($this->request->is(‘post’)) {
$user = $this->Auth->identify();
if ($user) {
if ($user[‘is_active’] === 1) {
$users = $this->Users->get($user[‘id’]);
$users->ip_address = $this->request->clientIp();
$users->last_login = date(‘Y-m-d h:i:s’);
if ($this->Users->save($users)) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Flash->error((‘Unable to login by your credentials.’));
}
} else {
$this->Flash->error((‘This user not activated, please contact our administrator.’));
}
}
$this->Flash->error(__(‘Invalid username or password, try again’));
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
}
After opening forgot password page user enter their email following error received.
Cannot instantiate abstract class Cake\Mailer\Mailer
How do I solve this problem when the user entered their email & reset password will be sent to user's email which will be saved in our database.
Help me please #ndm
In your app.php
use Cake\Mailer\Transport\MailTransport;
.
.
.
'EmailTransport' => [
'default' => [
'className' => MailTransport::class,
/*
* The following keys are used in SMTP transports:
*/
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => null,
'password' => null,
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
'your_project' => [
'className' => 'Smtp',
'host' => 'your_host',
'port' => XXX,
'timeout' => 30,
'username' => 'your_email',
'password' => 'your_password',
'client' => null,
'tls' => true,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
],
'Email' => [
'default' => [
'transport' => 'default',
'from' => 'you#localhost',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
],
'your_project' => [
'transport' => 'your_project',
'from' => ['your_email#teste.com' => 'My Site'],
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
],
],
Create a folder "Mailer" in src/Mailer. Create an UserMailer.php file
<?php
namespace App\Mailer;
use Cake\Mailer\Mailer;
class UserMailer extends Mailer
{
public static $name = 'User';
public function reset($user)
{
$this->to($user->email)
->profile('your_project')
->emailFormat('html')
->template('your_project', 'user')
->layout('user')
->viewVars(['name' => $user->name])
->subject(sprintf('Welcome...', $user->name))
->message("texte...");
}
}
In this case, I created a layout for my email. Create an "Email" folder in the layout.
On your controller, do the following:
$this->getMailer('User')->send('reset', [$user]);
Don't forget to import into the controller:
use Cake\Mailer\MailerAwareTrait;
I use it like this.
Go to the godaddy dashboard and find the SMTP information. It's all you need! Replace with your information

How to encrypt a password in cakephp 2.x version

Hello everyone i am using cakephp 2.x, as i am new to here, i need to encrypt my password before it stores to database
User.ctp : I am posting like this to post
<?php
echo $this->Form->input('password',array('type'=>'password','label'=>false,'div'=>false,'class'=>'form-control','id'=>'password'));
?>
Controller:
public function setting()
{
$this->layout='setting_template';
if($this->Session->read('username')==""){
$this->redirect(array('action' => 'user_login'));
}
elseif ($this->Session->read('username') == "admin" )
{
if($this->request->is('post'))
{
$this->data['password'] = encrypt($this->data ['password']);
if ($this->Login->save($this->request->data)) {
$this->Session->setFlash('The user has been saved');
$this->redirect(array('action' => 'setting'));
} else {
$this->Session->setFlash('The user could not be saved. Please, try again.');
}
}
$opp=$this->Login->find('all');
$this->set('login',$opp);
}
else{
echo "<script type='text/javascript'> alert('Permission Denied'); </script>";
$this->redirect(array('action' => 'index'));
}
}
Login controller:
public function login()
{
$this->layout='login_template';
if($this->data)
{
$this->Session->write('id',$this->data['Login']['id'] );
$results = $this->Login->find('first',array('conditions' => array('Login.password' => $this->data['Login']['password'],'Login.username' => $this->data['Login']['username'])));
$this->Session->write('name',$results['Login']['name']);
if ($results['Login']['id'])
{
$this->Session->write($this->data['Login']['username'].','. $this->data['Login']['password']);
$this->Session->write('username',$this->data['Login']['username']);
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash("error");
}
}
How can i encrypt the password file and also how can use the Model
As you are using CakePhp go with framework's best practices.
When creating new user records you can hash a password in the
beforeSave callback of your model using appropriate password hasher
class:
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
public function beforeSave($options = array()) {
if (!empty($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
}
You don’t need to hash passwords before calling $this->Auth->login(). The various authentication objects will hash passwords individually.
If you are using different model than User for authentication you need to define that in AppController. In your Case you need to do something like this in AppController:
$this->Auth->authenticate = array(
'Form' => array('userModel' => 'Login')
);
If you wish to hash your password, try this:
$hashedPassword = AuthComponent::password('original_password');
See Here :Cakephp Password Hashing.

When I click on login button it is directly going into else part in cakephp

if I click on login button, it is taking empty input values since the condition is directly going into else part of cakephp.
Below is the code:
if($this->request->is('post'))
{
if(isset($this->data['Loginsubmit']))
{
if($this->data['Reg']['email']=='')
{
echo 'hii';
}
elseif( $this->data['Reg']['password']=='')
{
echo "hi";
}
else
{
$result = $this->Reg->find('list',array('conditions'=>array('email'=>$this->request->data['Reg']['email'], 'password'=>$this->request->data['Reg']['password'],'status'=>1)));
pr($result);
if(!empty($result)){
$email=$this->request->data['Reg']['email'];
$this->Session->write('Reg', $result);
$this->redirect(array('action' => 'login'));}
else{$this->Flash->error("invalid");
}
$result = $this->Reg->find('all');
$this->set('results',$result);
}
Hi please do like this:
public function beforeFilter() {
parent::beforeFilter();
// Allow users to register and logout.
$this->Auth->fields = array(
'email' => 'email',
'password' => 'secretword'
);
}
public function login() {
if(!$this->Auth->Reg('id')){
$this->layout="login";
if ($this->request->is('post')) {
App::uses('Validation', 'Utility');
$user=0;
if(Validation::email($this->request->data['email']))
$user = $this->Reg->find('first', array(
'conditions' => array( 'Reg.email' => $this->request->data['email'],
),'recursive' => -1 ));
if($user)
{
$this->request->data['email']=$user['Reg']['email'];
}
$this->request->data=array('Reg'=>$this->request->data);
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
else
{
return $this->redirect($this->Auth->redirectUrl());
}
}
Please review & share your feedback.

Login Redirect with cakephp

I am current using Usermgmt Plugin for the login function and the users management. What I want to do is to redirect the specific pages based on the group_id after they login. I am current lost with the cake.
This is the code from AppController.
var $helpers = array('Form', 'Html', 'Session', 'Js', 'Usermgmt.UserAuth');
public $components = array('Session','RequestHandler', 'Usermgmt.UserAuth');
function beforeFilter(){
$this->userAuth();
}
private function userAuth(){
$this->UserAuth->beforeFilter($this);
}
This is the login function from UsersController.
public function login() {
if ($this->request -> isPost()) {
$this->User->set($this->data);
if($this->User->LoginValidate()) {
$email = $this->data['User']['email'];
$password = $this->data['User']['password'];
$user = $this->User->findByUsername($email);
if (empty($user)) {
$user = $this->User->findByEmail($email);
if (empty($user)) {
$this->Session->setFlash(__('Incorrect Email/Username or Password'));
return;
}
}
// check for inactive account
if ($user['User']['id'] != 1 and $user['User']['active']==0) {
$this->Session->setFlash(__('Your registration has not been confirmed please verify your email or contact to Administrator'));
return;
}
$hashed = md5($password);
if ($user['User']['password'] === $hashed) {
$this->UserAuth->login($user);
$remember = (!empty($this->data['User']['remember']));
if ($remember) {
$this->UserAuth->persist('2 weeks');
}
$OriginAfterLogin=$this->Session->read('Usermgmt.OriginAfterLogin');
$this->Session->delete('Usermgmt.OriginAfterLogin');
$redirect = (!empty($OriginAfterLogin)) ? $OriginAfterLogin : loginRedirectUrl;
$this->redirect($redirect);
} else {
$this->Session->setFlash(__('Incorrect Email/Username or Password'));
return;
}
}
}
}
Any help is appreciated. Thank you.
If you want to redirect them somewhere else, then change the redirect line. This assumes your User model is related to a Group model and the recursive level lets your find call pull the data.
// original
$redirect = (!empty($OriginAfterLogin)) ? $OriginAfterLogin : loginRedirectUrl;
// new redirect, eg: /groups/view/3
$redirect = array(
'controller' => 'groups',
'action' => 'view',
$user['Group']['id']
);
$this->redirect($redirect);

Using username instead of email in CakePHP's Auth Component

Using CakePHP's Auth Component, how do I allow users to authenticate by using either their "username" or "email" field as a username, and a "pass" field as their password?
what does "using (username and email) both as username " mean?
Edit: ok, so you want Auth to look in both username and email fields in the db to compare to the "username" that the user enters? then do this:
function beforeFilter() {
parent::beforeFilter();
$this->Auth->fields = array('username' => 'username', 'password' => 'pass');
$this->Auth->autoRedirect = false;
}
function login(){
if ($this->Auth->user()) {
$this->redirect($this->Auth->redirect());
} else if (!empty($this->data)) {
$this->Auth->fields = array('username' => 'email', 'password' => 'pass');
$this->data['User']['email'] = $this->data['User']['username'];
if($this->Auth->login($this->data))$this->redirect($this->Auth->redirect());
}
}
To do this you have to skip Auths autoredirect and manage it yourself. This the login action in your users_controller:
public function login() {
if(!empty($this->data)) { // Submitted form
// Try to login with Email
if(!$this->Auth->user() // if user wasn't logged in with username + pass
&& !empty($this->Auth->data['User']['username'])
&& !empty($this->Auth->data['User']['password'])
) {
$user = $this->User->find('first', array(
'conditions' => array(
'User.email' => $this->Auth->data['User']['username'],
'User.password' => $this->Auth->data['User']['password']
),
'recursive' => -1
));
if(!empty($user) && $this->Auth->login($user)) {
// They logged in, so kill the flash error message
$this->Session->delete('Message.auth');
} else {
$this->Session->setFlash($this->Auth->loginError, $this->Auth->flashElement, array(), 'auth');
}
}
if($this->Auth->user()) {
// Post login logic here
$this->redirect($this->Auth->redirect());
}
} else {
if($this->Auth->user()) {
$this->Session->setFlash(__d('users', 'You are already registered and logged in!', true));
//$this->redirect('/');
$this->redirect($this->Auth->redirect());
}
}
This was copied straight from my app, so may need a bit of tweaking for yours. Don't forget to set $this->Auth->autoRedirect = false; in your AppController:beforeFilter();
You have to remember that Auth will automatically check against username and password, so this action just picks up from that. The Session::remove() call is to delete the Auth error message automatically left when the username/password check fails ANd the email login succeeds (otherwise you get error messages with successful logins).

Resources