I want to implement a backend user management but how can i set up a hased password for a user?
my controller:
public function store(Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'password' => 'required', 'surname' => 'required', ]);
$user = new User($request->all());
$user->password=bcrypt($request);
$user->save();
return redirect('dash/users');
}
view
<div class="form-group {{ $errors->has('password') ? 'has-error' : ''}}">
{!! Form::label('password', trans('users.password'), ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('password', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('password', '<p class="help-block">:message</p>') !!}
</div>
</div>
fixed now, the function work and my new user are stored in database, but when i try to login with them the loginform say me "nothing record found"
why?
You need to pass the password text to bcrypt instead of whole $request
$user->password=bcrypt('yourpasswordtext');
<?php
namespace App\Http\Controllers\Dash;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
use App\User;
use App\Report;
use App\Category;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Session;
class UsersController extends Controller
{
/**
* Display a listing of the resource.
*
* #return void
*/
public function index()
{
$users = User::paginate(15);
return view('dash.users.index', compact('users'));
}
/**
* Show the form for creating a new resource.
*
* #return void
*/
public function create()
{
return view('dash.users.create');
}
/**
* Store a newly created resource in storage.
*
* #return void
*/
public function store(Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'password' => 'required', 'surname' => 'required', ]);
$user = new User($request->all());
$user->password = bcrypt($request);
$user->save();
return redirect('dash/users');
}
/**
* Display the specified resource.
*
* #param int $id
*
* #return void
*/
public function show($id)
{
$user = User::findOrFail($id);
return view('dash.users.show', compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
*
* #return void
*/
public function edit($id)
{
$user = User::findOrFail($id);
return view('dash.users.edit', compact('user'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
*
* #return void
*/
public function update($id, Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'password' => 'required', 'surname' => 'required', ]);
$user = User::findOrFail($id);
$user->update($request->all());
Session::flash('flash_message', 'User updated!');
return redirect('dash/users');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
*
* #return void
*/
public function destroy($id)
{
User::destroy($id);
Session::flash('flash_message', 'User deleted!');
return redirect('dash/users');
}
}
update, this is controller
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
/* ruote for Admin */
Route::group(['middleware' => ['web']], function () {
Route::resource('dash/reports', 'Dash\\ReportsController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/categories', 'Dash\\CategoriesController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/roles', 'Dash\\RolesController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/permissions', 'Dash\\PermissionsController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/users', 'Dash\\UsersController');
});
/* another routes */
Route::auth();
Route::get('/provola', 'HomeController#autorizzazione');
Route::get('/home', 'HomeController#index');
Route::get('/', function () {return view('welcome');});
/* injection for user roles
Route::get('/start', 'HomeController#inject');
*/
my routes
For Laravel 5.6+
Password should be hashed using Hash::make($password)
Related
i want to redirect to a previously accessed page right before accessing the registration page after a user has successfully registered themselves. I edited the registration controller as below although i get the following exception View [http:..127.0.0.1:8000.prices] not found. I cross checked my routes and everything is fine. Here is my register controller.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'fname' => ['required', 'string', 'max:255'],
'lname' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'phonenumber' => ['required', 'string', 'min:10', 'max:10'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'fname' => $data['fname'],
'lname' => $data['lname'],
'email' => $data['email'],
'phonenumber' => $data['phonenumber'],
'password' => Hash::make($data['password']),
]);
}
/**
* Show the application's registration form.
*
* #return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
if(session('link')) {
$myPath = session('link');
$registerPath = url('/register');
$previous = url()->previous();
if($previous = $registerPath) {
session(['link' => $myPath]);
}else{
session(['link' => $previous]);
}
}else{
session(['link' => url()->previous()]);
}
return view('auth.register');
}
protected function redirectTo()
{
if(session('link')){
return view(session('link'));
}
return view('/');
}
}
I think the issue is most likely to be with the function:
protected function redirectTo()
{
if(session('link')){
return view(session('link'));
}
return view('/');
}
I tried replacing return view(session('link')); with return url()->previous(); but there was no luck. I am using laravel 7.
The issue was actually with adding view. Instead of return view(session('link')); use return (session('link')); Same applies to the return outside the if statement.
try to use redirect back
return Redirect::back();
do not forget to import redirect in controller
use Redirect;
I am using password for user Authentication, and I after every authentication I assign a secure cookie that stores the passport token. A am being able to successfully authenticate using the Auth::attempt() method, but the Auth::user() is null. Even in the same controller, on the logout() method the user is undefined and I can't even Auth::logout().
Login method:
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
]);
$credentials = \request(['email', 'password']);
if (Auth::attempt($credentials)) {
$user = Auth::user();
$token = $user->createToken('Personal Access Token')->accessToken;
$cookie = $this->getSessionCookie($token);
return response()
->json([
'user' => $user,
'token' => $token,
], 200)
->cookie(
$cookie['name'],
$cookie['value'],
$cookie['minutes'],
$cookie['path'],
$cookie['domain'],
$cookie['secure'],
$cookie['httponly'],
$cookie['samesite']
);
} else {
return response()->json([
'error' => 'Invalid Credentials',
], 422);
}
}
Logout method:
public function logout(Request $request)
{
$request->user()->token()->each(function ($token, $key) {
$token->delete();
});
$cookie = \Cookie::forget('auth_token');
Auth::logout();
return response()->json([
'message' => 'Logged out successfully.'
], 200)->withCookie($cookie);
}
Here the Auth::logout() produces Method Illuminate\Auth\RequestGuard::logout does not exist. Otherwise the logout is successful.
My API routes:
Route::group(['prefix' => 'v1'], function() {
// Authentication
Route::post('/login', 'AuthController#login');
Route::post('/register', 'AuthController#register');
Route::post('/password/reset', 'AuthController#sendPasswordResetLink');
Route::post('/password/update', 'AuthController#callResetPassword');
// Articles
Route::get('/articles', 'ArticleController#index');
Route::middleware(['auth.header', 'auth:api'])->group(function () {
// Get Logged in User
Route::get('/user', function (Request $request) {
return $request->user(); // returns the actual logged in user
});
// Articles
Route::post('/articles', 'ArticleController#store');
Route::get('/articles/{id}', 'ArticleController#show');
Route::put('/articles/{id}', 'ArticleController#update');
Route::delete('/articles/{id}', 'ArticleController#destroy');
// Log Out
Route::post('/logout', 'AuthController#logout');
});
});
Example controller where Auth::user() is null:
class ArticleController extends Controller
{
public function index(Request $request)
{
$user = \auth()->user(); // null
$user = Auth::user(); // null
$user = $request->user(); // null
}
}
In index method I know why the user is null since the route is not wrapped in auth:api middleware, but how would I get the auth user in this method even if it's not required.
I am sure I am missing something but I don't know what. I'll be happy to provide more code.
EDIT:
My auth.api middleware:
class AuthenticationHeader
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!$request->bearerToken()) {
if ($request->hasCookie('auth_token')) {
$token = $request->cookie('auth_token');
$request->headers->add(['Authorization' => 'Bearer ' . $token]);
}
}
return $next($request);
}
}
API Routes
Route::group(['prefix' => 'v1'], function() {
// Authentication
Route::post('/login', 'AuthController#login');
Route::post('/register', 'AuthController#register');
Route::post('/password/reset', 'AuthController#sendPasswordResetLink');
Route::post('/password/update', 'AuthController#callResetPassword');
// Articles
Route::get('/articles', 'ArticleController#index');
Route::middleware(['auth:api'])->group(function () {
// Get Logged in User
Route::get('/user', function (Request $request) {
return $request->user(); // returns the actual logged in user
});
// Articles
Route::post('/articles', 'ArticleController#store');
Route::get('/articles/{id}', 'ArticleController#show');
Route::put('/articles/{id}', 'ArticleController#update');
Route::delete('/articles/{id}', 'ArticleController#destroy');
// Log Out
Route::post('/logout', 'AuthController#logout');
});
});
Auth Controller
<?php
namespace App\Http\Controllers\Api;
use App\Mail\ResetPassword;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\BaseController as BaseController;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;
use Illuminate\Support\Facades\Password;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Foundation\Auth\ResetsPasswords;
//use Illuminate\Foundation\Auth\VerifiesEmails;
//use Illuminate\Auth\Events\Verified;
class AuthController extends BaseController
{
use ResetsPasswords;
/**
* Authenticate api
* #param Request
* #return \Illuminate\Http\Response
*/
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors(), 400);
}
$email = $request->input('email');
$password = $request->input('password');
if (Auth::attempt(['email' => $email, 'password' => $password])) {
$user = Auth::user();
if ($user->hasVerifiedEmail()) {
$success['token'] = 'Bearer ' . $user->createToken('MyApp')->accessToken;
$success['user'] = $user->only('id', 'name', 'email', 'avatar');
return $this->sendResponse($success, 'User logged in successfully.');
} else {
return $this->sendError('Please verify your Email.', [], 400);
}
}
return $this->sendError('Wrong Credentials.', [], 400);
}
/**
* Register API
* #param Request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
//'g-recaptcha-response' => 'required|captcha',
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors(), 400);
}
$name = $request->input('name');
$email = $request->input('email');
$password = $request->input('password');
$user = User::where('email', $email)->first();
if ($user) {
return $this->sendError('This email address is already taken. Please try another.', [], 400);
}
$user = User::create([
'name' => $name,
'email' => $email,
'password' => bcrypt($password)
]);
$user->sendApiEmailVerificationNotification();
return $this->sendResponse([], 'Please confirm yourself by clicking on verify user button sent to you on your email.');
}
/**
* Send reset password email API
* #param Request
* #return \Illuminate\Http\Response
*/
public function sendPasswordResetLink(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors(), 400);
}
$email = $request->input('email');
$response = Password::sendResetLink(['email' => $email], function (Message $message) {
$message->subject($this->getEmailSubject());
});
switch ($response) {
case Password::RESET_LINK_SENT:
return $this->sendResponse([], 'We have e-mailed your password reset link!');
case Password::INVALID_USER:
return $this->sendError('We can\'t find a user with that e-mail address.', [], 400);
}
}
/**
* Reset password action API
* #param Request
* #return \Illuminate\Http\Response
*/
public function callResetPassword(Request $request)
{
$validator = Validator::make($request->all(), [
'token' => 'required',
'email' => 'required|email',
'password' => 'required',
'password_confirmation' => 'required|same:password',
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors(), 400);
}
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request),
function ($user, $password) {
$this->resetPassword($user, $password);
}
);
if ($response == Password::PASSWORD_RESET) {
return $this->sendResponse([], 'User password has been successfully reset.');
} else {
return $this->sendError($response, [], 400);
}
}
/**
* Logout API
* #param Request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
if (Auth::check()) {
Auth::user()->oauthAcessTokens()->delete();
return $this->sendResponse([], 'User logged out successfully.');
}
}
}
Base Controller
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class BaseController extends Controller
{
/**
* success response method.
*
* #return \Illuminate\Http\Response
*/
public function sendResponse($result, $message = null)
{
$response = [
'success' => true,
'data' => $result
];
if (!empty($message)) {
$response['message'] = $message;
}
return response()->json($response, 200);
}
/**
* return error response.
*
* #return \Illuminate\Http\Response
*/
public function sendError($error, $errorMessages = [], $code = 422)
{
$response = [
'success' => false,
'message' => $error,
];
if (!empty($errorMessages)) {
$response['data'] = $errorMessages;
}
return response()->json($response, $code);
}
}
I tested my app to disallow duplication of emails. It works, however I can't catch the error or it doesn't display the request error in the form page whenever it found duplication.
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
'admin#DOMAIN.com' for key 'admins_email_unique'
I already tried overriding the RegisterController, but still can't find where the error is being fetch first.
protected function create(array $data)
{
try{
return Admin::create([
'role_id' => $data['role_id'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
catch(Illuminate\Database\QueryException $e)
{
echo($e);
}
}
My current RegisterController
<?php
namespace App\Http\Controllers\AdminAuth;
use App\Admin;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Traits\RoleTrait;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
use RoleTrait;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/admin/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('admin.guest');
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return Admin::create([
'role_id' => $data['role_id'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'role_id' => 'required|string|max:4',
'username' => 'required|string|unique:users|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Show the application registration form.
*
* #return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
$mgaAdminRoleNames = $this->getAdminRoleNames();
return view('admin.auth.register')->with('adminRoleNames',$mgaAdminRoleNames);
}
/**
* Get the guard to be used during registration.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard('admin');
}
I already put in admin\auth\register.blade.php
#if ($errors->has('email'))
<span class="invalidMessage">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
The expected solution either of this two:
1) Display error in the form page like this:
Image Here
2) Or catch the QueryException and echo the error directly
use validations for duplicate entry i hope this link will be helpful laravel recommended link
I found an answer while I'm checking the validator. So if anyone encounter this problem. Here's the solution:
protected function validator(array $data)
{
return Validator::make($data, [
'role_id' => 'required|string|max:4',
'username' => 'required|string|unique:admins|max:255',
'email' => 'required|string|email|max:255|unique:admins',
'password' => 'required|string|min:6|confirmed',
]);
}
Notice the "unique" attribute. I change it from "users" to "admins".
I think the word "admins" came from config\auth.php directory where you set your guards and providers stuff.
I am using Laravel 5.5.14 (php artisan --version). I am using Laravel to create just a REST API.
When I get errors, the shape of it looks like this:
[
'message' => 'The given data was invalid.',
'errors' => [
'email' => ['The email field is required.'],
'password' => ['The password field is required.']
]
]
My
We see inside the errors array, each field (email, password) instead of being strings, is an array of a single string. Can there ever be more then one error is this why it is an array? Even if there is more then one error, I wanted to tell Laravel just report the first error without an array, is this possible?
In my api.php I have this:
Route::post('login', 'Auth\LoginController#login');
Route::post('logout', 'Auth\LoginController#logout');
Route::post('register', 'Auth\RegisterController#register');
My LoginController.php looks like this:
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->attemptLogin($request)) {
$user = $this->guard()->user()->load('pets');
$user->generateToken();
return $user;
}
return $this->sendFailedLoginResponse($request);
}
public function logout(Request $request)
{
$user = Auth::guard('api')->user();
if ($user) {
$user->api_token = null;
$user->save();
}
return ['ok' => true];
}
And my RegisterController.php looks like this:
public function __construct()
{
$this->middleware('guest');
}
/**
* The user has been registered.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function registered(Request $request, $user)
{
$user->generateToken();
return response()->json($user, 201);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
Override validateLogin to the following or you could give it a different name and call it from your controller function-
public function validateLogin($request){
$rules = [
'user_name' => 'required|string',
'password' => 'required|string',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
$errorResponse = $this->validationErrorsToString($validator->errors());
return response()->json(['message' => 'The given data was invalid.', 'errors' => $errorResponse],400);
}
}
And make another function to transform your response to expected format with this method-
private function validationErrorsToString($errArray) {
$valArr = array();
foreach ($errArray->toArray() as $key => $value) {
$valArr[$key] = $value[0];
}
return $valArr;
}
And don't forget to add this at the start of your controller file-
use Validator;
Hope this helps you :)
From the docs:
The $errors variable will be an instance of Illuminate\Support\MessageBag
An example of displaying errors from the docs:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
I am trying to click on logout button, but it returns an error:
NotFoundHttpException in RouteCollection.php line 161:
There's no getLogout in Authcontroller, and it worked before, not sure why now it isn't.
AuthController:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = "dashboard";
protected $loginPath = 'auth/login';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'username' => 'required|max:20|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
]);
}
}
Routes.php:
Route::get('auth/logout', 'Auth\AuthController#getLogout');
view:
Logout
Try
Logout
Or give your route a name
Route::get('auth/logout', ['as' => 'logout', 'uses' => 'Auth\AuthController#getLogout');
and do
Logout