I want to implement user roles for my controller. When the user is admin or master it works, but when the user is a client it doesn't, and I receive a 205 http response.
This code works nicely in my localhost but it doesn't so in my host.
public function store(Request $request)
{
$validation = Validator::make($request->all(), [
'name' => 'required|string',
'imageone'=> 'required|string'
]);
if ($validation->fails())
{
return response()->json('Fails',404);
}
$user = JWTAuth::parseToken()->authenticate();
if ($user->roles=='admin'||$user->roles=='master') {
$name= $request->input('name');
$imageone = $request->input('imageone');
$cate=new categoryi();
$cate->name=$name;
$cate->imageone=$imageone;
if ($cate->save())
{
return response()->json($cate,202);
}
}
return response()->json('Fails',500);
}
Related
I'm trying to make login with google using laravel socialite and I have a problem.
Route that initiates login:
Route::get('/auth/login/google', 'AuthController#google');
Method in controller that initiates login:
public function google()
{
return Socialite::driver('google')->redirect();
}
Callback route:
Route::get('/auth/login/google/redirect', 'AuthController#googleRedirect');
Callback method in controller:
public function googleRedirect()
{
$googleUser = Socialite::driver('google')->user();
$email = $googleUser->getEmail();
$user = new User();
$user = $user->firstOrCreate(['email' => $email], ['email' => $email, 'password' =>
bcrypt(str_shuffle('abcdefgh45678')), 'email_verified' => 1]);
Auth::login($user, true);
}
And I'm getting ERR_EMPTY_RESPONSE every time I'm trying to redirect user after login.
Funny thing is that I can dump data with dd(Auth::user()->id) and I'm getting user's ID, but when I try to redirect user to the home page using return redirect('/') I'm getting empty response error and if I manually go to home page my user is not authenticated.
#Matej Petric blow code is working for me.
public function handleProviderCallback($provider) {
$user = Socialite::driver('google')->stateless()->user();
$authUser = $this->findOrCreateUser($user);
if ($authUser) {
Auth::login($authUser, true);
return redirect('/');
} else {
return redirect('/login')->withErrors(['msg', 'The Message']);
}
}
public function findOrCreateUser($user) {
$authUser = User::where('email', $user->email)->first();
if ($authUser) {
return $authUser;
}
$userN = User::create([
'name' => $user->name,
'email' => $user->email,
'password' => bcrypt(generateRandom()),
]);
return $userN;
}
I have one form in frontend where I have there is some city details , rooms details and user registration in one form like I have city name , room name , address etc email addresss and password in same form and I have done 2 logics in one controller for creating cities and registering user
It is saving the both data in correct table in the database
but I want that first user should register and if user is vcerified only the room details should be saved in database
I am in confusion wheather to apply if again or what
public function checkLogin(Request $request)
{
$user = User::create([
'name'=>$request->name,
'email'=>$request->email,
'password'=>$request->password,
'role_id' => config('quickadmin.default_role_id'),
]);
if ($user) {
if (Auth::check()) {
$city = TotalCity::create([
'name'=>$request->name,
'created_by'=>$request->created_by_id,
]);
}
return redirect()->to('/admin/home');
}
}
Let me show you how I'd probably write this logic:
public function checkLogin(Request $request)
{
$user = User::firstOrCreate([
'email'=> $request->email,
],
[
'name'=> $request->name,
'password'=> bcrypt($request->password),
'role_id' => config('quickadmin.default_role_id'),
]);
if (Auth::check()) {
// it's not clear if you utilize `email_verified_at`, if so
// if (Auth::check() && Auth::user()->email_verified_at) {
$city = TotalCity::create([
'name'=>$request->name,
'created_by'=> Auth::user()->id, // or $user->id depending on your preference
]);
}
return redirect('/admin/home');
}
The firstOrCreate() checks if an entry with that email exists, it gets it, otherwise creates it.
Furthermore, if I want to check for Authentication, I'd use 'auth' middleware in my route.
Route::get('example', 'ExampleController#checkLogin')->middleware('auth');
That removes the need of entire check:
if (Auth::check()) { ... }
I'm using this to flash error messages within my UserController (using Toastr);
public function update(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|max:200',
'email' => 'required|email|unique:users,email,'. Auth::id(),
'phone' => 'alpha_num|nullable|min:8',
]);
if ($validator->fails()) {
Toastr::error('Changes not saved', 'Error');
return back();
}
$user = Auth::user();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->phone = $request->input('phone');
$user->save();
Toastr::success('Changes saved', 'OK');
return back();
}
I would like to use Form Request for my validation, but keep running into problems when trying to flash (toastr) error messages.
Do one of you have an example of toastr used with Form Request? I have read the documentation like 10 times, but can't find a solution :(
https://laravel.com/docs/5.7/validation
This used to work about a year ago, but not anymore:
# Error messages
protected function formatErrors(Validator $validator)
{
$messages = $validator->messages();
foreach ($messages->all() as $message)
{
Toastr::error($message, 'Fejl');
}
return $validator->errors()->all();
}
Use withValidator() in your form request
but I am using toaster package from yoeunes/toastr
public function withValidator($validator)
{
$messages = $validator->messages();
foreach ($messages->all() as $message)
{
toastr()->error ( $message, 'Error');
}
return $validator->errors()->all();
}
It works for me in Laravel 7.x
Try that, thanks!
I am working in laravel 5.1 and my update profile was working but will not encrypted and not working now.
When I try to update the user table will also password_confirmation field and causes a conflict in the database. I do not understand.
In the form says successfully but the database does not update any
Code
public function updatePassword() {
$passwordData = Input::except('_token');
$validation = Validator::make($passwordData, User::$passwordData);
if ($validation->passes()) {
array_forget($passwordData,'password_confirmation');
User::where(array(
'password' => Hash::make(Input::get('password'))
));
Session::flash('password', 'Perfil editado com sucesso');
return Redirect::to('backend/perfil/password');
} else {
return Redirect::to('backend/perfil/password')->withInput()->withErrors($validation);
}
}
user
public static $passwordData = array(
'password' => 'required|confirmed',
'password_confirmation' => 'required'
);
Follow this simple steps to get rid of anything
Step 1 : Get the password from the form
$PasswordData = Input::all();
Step 2 : Validate your password
Validator::extend('pwdvalidation', function($field, $value, $parameters) {
return Hash::check($value, Auth::user()->password);
});
Step 3 : Define the validation rule in your User Model
public static $rulespwd = array('OldPassword' => 'required|pwdvalidation',
'NewPassword' => 'required|confirmed|alphaNum|min:5|max:10',
'NewPassword_confirmation' => 'required',
);
Note : You shall define your own rule according to your need
Step 4 : If the rule is passed, then update else throw error messages to your view
$validator = Validator::make($PasswordData, User::$rulespwd, $messages);
if ($validator->passes()) {
$user = User::find(Auth::user()->id);
$user->password = Input::get('NewPassword');
$user->save();
return Redirect::to(Session::get('urlpath') . '/changepassword')->withInput()->with('Messages', 'The Password Information was Updated');
} else {
return Redirect::to(Session::get('urlpath') . '/changepassword')->withInput()->withErrors($validator);
}
I have a Personcontroller and a Festivalcontroller in my laravel4 application. The actions in those controllers can only be accessible by an administrator.
If my database only has a user with test#hotmail.com, that user can access the routes of those 2 controllers. If my database has no user with test#hotmail.com, but it has other users, those other users can't access the routes of those 2 controllers. And when my database has a user with test#hotmail.com, and has other users, everyone can access the routes of those 2 controllers.
I only want the user with email test#hotmail.com to access the routes of those controllers.
I installed Sentry2 by doing this:
In composer.json file require:
"cartalyst/sentry": "2.0.*"
Run
php composer.phar update
In app > config > app.php:
'Cartalyst\Sentry\SentryServiceProvider', => to the providers array
'Sentry' => 'Cartalyst\Sentry\Facades\Laravel\Sentry', => to the aliases array
After the installation I made the SentrySeeder file:
<?php
class SentrySeeder extends Seeder {
public function run()
{
DB::table('users')->delete();
DB::table('groups')->delete();
DB::table('users_groups')->delete();
Sentry::getUserProvider()->create(array(
'email' => 'test#hotmail.com',
'password' => "test",
'activated' => 1,
));
$user = Sentry::getUserProvider()->findByLogin('test#hotmail.com');
$adminGroup = Sentry::getGroupProvider()->findByName('Test');
$user->addGroup($adminGroup);
}
}
In my PersonController
class PersonController extends BaseController {
public function index()
{
try
{
$user = Sentry::findUserByLogin('test#hotmail.com');
if ($user)
{
$person = Person::with('user')->orderBy('person_id')->paginate(10);
return View::make('persons.index')
->with('person', $person);
}
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
echo 'User was not found.';
}
}
}
Login action in LoginController
public function login()
{
$input = Input::all();
$rules = array(
'user_email' => 'required',
'user_password' => 'required'
);
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('user_password'));
}
else {
$attempt = Auth::attempt([
'user_email' => $input['user_email'],
'password' => $input['user_password']
]);
if ($attempt) {
return Redirect::to('/home');
}
else {
return Redirect::to('login');
}
}
Store a user in database
public function store()
{
$input = Input::all();
$rules = array(
'user_email' => 'required|unique:users|email',
'user_username' => 'required|unique:users',
);
$validator = Validator::make($input, $rules);
if($validator->passes())
{
$password = $input['user_password'];
$password = Hash::make($password);
$location = new Location();
$person = new Person();
$user = new User();
$person->person_firstname = $input['person_firstname'];
$person->person_surname = $input['person_surname'];
$user->user_username = $input['user_username'];
$user->user_email = $input['user_email'];
$user->user_password = $password;
$location->save();
$person->save();
$user->location()->associate($location);
$user->person()->associate($person);
$user->save();
Session::flash('message', 'Successfully created user!');
return Redirect::to('login');
}
else {
return Redirect::to('persons/create')->withInput()->withErrors($validator);
}
}
Looks like you need to use your own users table and also use Sentry's. So you'll need to add related Sentry's columns to yours. It's easy:
1) Go to vendor\cartalyst\sentry\src\migrations.
2) Create one new migration for every file you see there, example:
php artisan migrate:make add_sentry_groups_table
3) Copy the up() and down() code (ONLY!) to your new migrations.
4) And, for the users migration, you'll have to do some changes:
Instead of Schema::create('users' ... you do Schema::table('users' ..., to add more columns to your table.
Delete all commands for columns that you alread have in your current users table, examples of lines you must delete:
$table->increments('id');
$table->timestamps();
5) Run a normal ´php artisan migrate´.
After that you should have the Sentry's tables ready to work.
EDIT
As you're not using the usual 'email' and 'password' columns, publish Sentry's configuration:
php artisan config:publish cartalyst/sentry
And alter
'login_attribute' => 'user_email',