I'm doing a login and registration screen, the registration screen is perfect, but the login screen is giving me a headache to authenticate.
the registration is done, but as soon as I log in it gives this error...
"Undefined property: Illuminate\Support\Facades\Request::$email"
I don't know what else to do to make it work.
CONTROLLER:
<?php
namespace App\Http\Controllers;
use App\Models\Usuario;
use Illuminate\Support\Facades\Auth;
use Request;
class Usuarios extends Controller
{
public function cadastrar()
{
$usuario = new Usuario(Request::all());
$usuario->save();
return redirect('/')->with('mensagem_sucesso', 'Cadastro efetuado com sucesso!');
}
public function index()
{
return view('layout/cadastrousuario');
}
public function indexlogin()
{
return view('layout/login');
}
public function logar(Request $request)
{
if (Auth::attempt(['email' => $request->email, 'password' => $request-> password])) {
dd('voce esta logado');
} else {
dd('voce nao esta logado');
}
}
}
MODEL:
<?php
namespace App\Models;
use App\Models\Model\Request;
use DB;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
class Usuario extends Authenticatable
{
protected $table = 'usuario';
public $timestamps = false;
protected $fillable =
array(
"codigo",
"nome",
"email",
"apelido",
"senha",
"bloqueado",
"saldo",
"saldo_atual",
"admin"
);
use HasFactory;
}
ROUTE:
<?php
use App\Http\Controllers\Lancamentos;
use App\Http\Controllers\LancamentosSimplificado;
use App\Http\Controllers\Usuarios;
use Illuminate\Support\Facades\Route;
// Route = (rota)::get ou post = (method) ( '/home' = (link) , [Lancamentos = (controller) :: class, 'logar' = ( function) ;
Route::get('/', [Lancamentos::class, 'index']);
Route::get('/salvar', [Lancamentos::class, 'salvar']);
Route::get('/maisdetalhes/{codigo}', [Lancamentos::class, 'maisdetalhes']);
Route::get('/criarchat', [Lancamentos::class, 'criarchat']);
Route::post('/cadastrar', [Lancamentos::class, 'cadastrar']);
Route::post('/cadastrar-simplificado', [LancamentosSimplificado::class, 'cadastrar']);
Route::get('/criarchat', [LancamentosSimplificado::class, 'listar']);
Route::get('/chat/{codigo}', [Lancamentos::class, 'chat']);
Route::get('/chatcriado/{codigo}', [LancamentosSimplificado::class, 'chatcriado']);
Route::get('/cadastrar-usuario', [Usuarios::class, 'index']);
Route::post('/cadastrar-usuario', [Usuarios::class, 'cadastrar']);
Route::get('/login', [Usuarios::class, 'indexlogin']);
Route::post('/login', [Usuarios::class, 'logar']);
page image as soon as I click login
to start you have to make validations in the register function to be sure that the email address arrives well and is registered. i would start by modifying this function
public function cadastrar(Request $r)
{
$r->validate([
'name' => 'required|string',
'email' => 'required|email|unique:users',
'password' => 'min:6',
'password_confirmation' => 'required_with:password|same:password|min:6',
'custom_field' => 'custom validation'
]);
$input = $r->all();
$input['password'] = Hash::make($r->password);
$utilisateur = Model::create($input); //the Model == Usuario;
return redirect('/')->with([
'message' => "Cadastro efetuado com sucesso!",
'alert-type' => 'success',
]);
}
this is just a code snippet, I don't pretend to say that it's exactly what you need.the next way is the login function
if (Auth::attempt(['email' => $r->email, 'password' => $r->password])) {
// The user is active, not suspended, and exists.
$user = Auth::user();
if($user->fcm_token != Null){
$token = $user->createToken('AUTH')->accessToken;
$user->remember_token = $token;
$user->device_token = $user->fcm_token;
$user->save();
$response = [
"data"=> [
'user'=> $user,
'token'=> $token,
],
'message_fr' => 'Utilisateur connecté avec succès',
'message_en' => 'User logged successfully',
];
return response()->json($response, 200);
}else{
$response = [
'message_fr' => 'Vous êtes peut-être un robot',
'message_en' => 'You may be a robot',
];
return response()->json($response, 422);
}
} else {
$response = [
'message_fr' => 'Veuillez vérifier vos informations de connexion',
'message_en' => 'Please check your login information',
];
return response()->json($response, 422);
}
since you put a validation on the register, you are sure that the email is not only present, but also conforms to the nomenclature of an email
these two methods presented are examples taken from my source code of an available project, Good luck to you
You are using the wrong Request class. Request (Illuminate\Support\Facades\Request) that is aliased in config/app.php is the Facade, static proxy, for the bound Request class instance, Illuminate\Http\Request. If you want an instance of a Request you need to be using Illuminate\Http\Request.
use Illuminate\Http\Request;
Now via dependency injection you will have an instance of the Request class (which has magic methods to access inputs via dynamic properties). If you keep what you have then you would not be asking for an instance via dependency injection and would have to use the Facade as a Facade:
public function logar()
{
...
$something = Request::input(...); // static call to Facade
...
}
Related
I made a controller "Login" to make token below and successfully, but I don't know how to catch that token for another controller
<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\UserModel;
use Firebase\JWT\JWT;
class Login extends ResourceController
{
/**
* Return an array of resource objects, themselves in array format
*
* #return mixed
*/
use ResponseTrait;
public function index()
{
helper(['form']);
$rules = [
'email' => 'required|valid_email',
'password' => 'required|min_length[6]'
];
if (!$this->Validate($rules)) return $this->fail($this->validator->getErrors());
$model = new UserModel();
$user = $model->where("email", $this->request->getVar('email'))->first();
if (!$user) return $this->failNotFound('Email Tidak Ditemukan');
$verify = password_verify($this->request->getVar('password'), $user['password']);
if (!$verify) return $this->fail('wrong Password');
$key = getenv('TOKEN_SECRET');
$payload = [
// issue at : kapan token dibuat
'iat' => 1356999524,
// non before : kapan expired
'nbf' => 1357000000,
'uid' => $user['id'],
'email' => $user['email'],
];
$token = JWT::encode($payload, $key, 'HS256');
return $this->respond($token);
// return redirect()->to(base_url('/me', $token));
}
}
I expect to know how the way to passing token from one controller to another
The token can't be passed to a different controller. Instead, the client (I'm assuming you're working in a API) should send the token as a parameter or as a header. The most common cases use Bearer Tokens
So I just want to add login with google feature on my working authentication web app (with Codeigniter Shield package). I've already create a login_google function on Login controller that extends LoginController from shield package like this :
LoginController
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\Shield\Controllers\LoginController;
class Login extends LoginController
{
function __construct()
{
require_once __DIR__ . '/../../vendor/autoload.php';
$this->userModel = new \App\Models\UserModel();
$this->google_client = new \Google_Client();
$this->google_client->setClientId(getenv('OAuth2.clientID'));
$this->google_client->setClientSecret(getenv('OAuth2.clientSecret'));
$this->google_client->setRedirectUri('http://localhost:8080/login_google');
$this->google_client->addScope('email');
$this->google_client->addScope('profile');
}
public function loginView()
{
if (auth()->loggedIn()) {
return redirect()->to(config('Auth')->loginRedirect());
}
/** #var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
// If an action has been defined, start it up.
if ($authenticator->hasAction()) {
return redirect()->route('auth-action-show');
}
$data['google_button'] = "<a href='".$this->google_client->createAuthUrl()."'><img src='https://developers.google.com/identity/images/btn_google_signin_dark_normal_web.png' /></a>";
return view('login', $data);
}
public function loginAction(): RedirectResponse
{
// Validate here first, since some things,
// like the password, can only be validated properly here.
$rules = $this->getValidationRules();
if (! $this->validate($rules)) {
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
$credentials = $this->request->getPost(setting('Auth.validFields'));
$credentials = array_filter($credentials);
$credentials['password'] = $this->request->getPost('password');
$remember = (bool) $this->request->getPost('remember');
/** #var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
// Attempt to login
$result = $authenticator->remember($remember)->attempt($credentials);
if (! $result->isOK()) {
return redirect()->route('login')->withInput()->with('error', $result->reason());
}
/** #var Session $authenticator */
$authenticator = auth('session')->getAuthenticator();
// If an action has been defined for login, start it up.
if ($authenticator->hasAction()) {
return redirect()->route('auth-action-show')->withCookies();
}
return redirect()->to(config('Auth')->loginRedirect())->withCookies();
}
public function login_google() {
$token = $this->google_client->fetchAccessTokenWithAuthCode($this->request->getVar('code'));
if (!isset($token['error'])) {
$this->google_client->setAccessToken($token['access_token']);
$this->session->set('access_token', $token['access_token']);
$google_service = new \Google\Service\Oauth2($this->google_client);
$data = $google_service->userinfo->get();
$userdata = array();
if ($this->userModel->isAlreadyRegister($data['id'])) {
$userdata = [
'first_name' => $data['givenName'],
'last_name' => $data['familyName'],
'email' => $data['email'],
'avatar' => $data['picture'],
];
$this->userModel->updateUserData($userdata, $data['id']);
} else {
$userdata = [
'first_name' => $data['givenName'],
'last_name' => $data['familyName'],
'email' => $data['email'],
'avatar' => $data['picture'],
'oauth_id' => $data['id'],
];
$this->userModel->insertUserData($userdata);
}
$this->session->set('LoggedUserData', $userdata);
} else {
$this->session->set("error", $token['error']);
return redirect('/register');
}
return redirect()->to('/profile');
}
}
UserModel like this :
UserMode
<?php
namespace App\Models;
use CodeIgniter\Model;
use CodeIgniter\Shield\Models\UserModel as ModelsUserModel;
class UserModel extends ModelsUserModel
{
protected $allowedFields = [
'username',
'status',
'status_message',
'active',
'last_active',
'deleted_at',
'gender',
'first_name',
'last_name',
'avatar',
'phone_number',
'full_address',
'oauth_id',
];
function isAlreadyRegister($authid){
return $this->db->table('users')->getWhere(['id'=>$authid])->getRowArray()>0?true:false;
}
function updateUserData($userdata, $authid){
$this->db->table("users")->where(['id'=>$authid])->update($userdata);
}
function insertUserData($userdata){
$this->db->table("users")->insert($userdata);
}
}
But everytime I clicked sign in with google button, it won't work (the interface for choosing google account to authenticate is worked) and always return to login page
am I missing something when combining CodeIgniter Shield with Google Oauth ? Anyone can help ? TIA
A new package has been created for OAuth with Shield package: https://github.com/datamweb/shield-oauth
You can use it instead of your own one.
I am using Laravel 5.4 with JWTAuth & Dingo and for some reason I am now no longer able to make POST requests with Postman. This was working when I first set it up, but not I get the response 405 Method Not Allowed
This seems to have been raised a few times on here, but I can't seem to find a solution. I've cleared the route cache, and when i do api:routes the correct routes are in there.
Below is the routes file, and the controllers it should be sending too. I am only having the issue with the LeadController routes.
api.php
use Dingo\Api\Routing\Router;
/** #var Router $api */
$api = app(Router::class);
$api->version('v1', function (Router $api) {
$api->group(['prefix' => 'auth'], function(Router $api) {
//$api->post('signup', 'App\\Api\\V1\\Controllers\\SignUpController#signUp');
$api->post('login', 'App\\Api\\V1\\Controllers\\LoginController#login');
$api->post('recovery', 'App\\Api\\V1\\Controllers\\ForgotPasswordController#sendResetEmail');
$api->post('reset', 'App\\Api\\V1\\Controllers\\ResetPasswordController#resetPassword');
});
$api->group(['middleware' => 'jwt.auth'], function(Router $api) {
$api->get('protected', function() {
return response()->json([
'message' => 'Access to protected resources granted! You are seeing this text as you provided the token correctly.'
]);
});
$api->get('refresh', [
'middleware' => 'jwt.refresh',
function() {
return response()->json([
'message' => 'By accessing this endpoint, you can refresh your access token at each request. Check out this response headers!'
]);
}
]);
$api->post('lead/store', 'App\\Api\\V1\\Controllers\\LeadController#store');
$api->get('lead', 'App\\Api\\V1\\Controllers\\LeadController#index');
});
});
LeadController.php
namespace App\Api\V1\Controllers;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tymon\JWTAuth\JWTAuth;
use App\Http\Controllers\Controller;
use Dingo\Api\Routing\Helpers;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Lead;
use App\User;
class LeadController extends Controller
{
use Helpers;
public function index(Lead $leads)
{
$leads = $leads->all();
$count = 0;
foreach($leads as $key => $lead){
$user = User::where('id', $lead->user_id)->first();
$leads[$count]['name'] = $user->name;
array_pull($leads[$count], 'user_id');
$count++;
}
return $leads;
}
public function store(Request $request)
{
$today = new Carbon();
$this->validate(request(), [
'owner' => 'required',
'bname' => 'required|min:3|max:255',
'tname' => 'max:255',
'created' => 'required|date|before_or_equal:today',
'update' => 'date'
]);
if(!$user = User::where('zoho_id', $request->get('owner'))->first())
return $this->response->error('invalid_owner', 500);
$lead = new Lead;
$lead->user_id = $user->id;
$lead->bname = $request->get('bname');
$lead->tname = $request->get('tname');
$lead->created_at = $request->get('created');
$lead->updated_at = $request->get('updated');
if($lead->save())
return $this->response->created();
else
return $this->response->error('could_not_create_lead', 500);
}
}
I found the answer, for this whilst I almost finished writing the question by stumbling upon the answer here:
https://laracasts.com/discuss/channels/laravel/dingo-api-and-postman-not-matching-post-request
Remove the trailing / from the request URL. So will leave this answer here, in the hopes it may prove useful to someone.
ie. http://api.someurl.app/api/lead/store?token=....
Perhaps, someone can suggest a way of allowing trailing / ??
I have a problem with Laravel 5.4 validator which is I'm trying to validate data comes from a mobile application but when validator fails it redirect to the home page. I need to prevent this redirect and return a json response with validation errors messages
Here's my route.php code
Route::group(['middleware' => 'web'], function() {
Route::post('/userSignUp', [
'uses' => 'UserController#userSignUp',
'as' => 'userSingUp'
]);
});
And this is my controller code
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
class UserController extends Controller
{
public function userSignUp(Request $request){
$fullName = $request->input('fullName');
$email = $request->input('email');
$phone = $request->input('phone');
$password = $request->input('password');
$userType = $request->input('userType');
$profilePic = $request->input('profilePic');
$validator = $this->validate($request, [
'fullName' => 'required|max:255',
'email' => 'required|email',
'phone' => 'required'
]);
if ($validator->fails()) {
return response()->json($validator->messages(), 200);
}
}
}
So can anyone help me solving this issue I need to use a laravel 5.4 validator in a web service for a mobile application so I need to prevent the validator redirecting as it does in the above code it redirecting to home page when validation is failed
thanks in advance
if the validation fails when you call $this->validate($request,$rules) laravel will throw an exception and a failed validation response will be sent back by this method define in Illuminate\Foundation\Validation\ValidatesRequests :
/**
* Create the response for when a request fails validation.
*
* #param \Illuminate\Http\Request $request
* #param array $errors
* #return \Symfony\Component\HttpFoundation\Response
*/
protected function buildFailedValidationResponse(Request $request, array $errors)
{
if ($request->expectsJson()) {
return new JsonResponse($errors, 422);
}
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
}
So it seems that Laravel does handle that by checking $request->expectsJson() so you need to specify the Accept header in you request to JSON, then a JSON formatted response with code 422 will be returned.
return response()
->json(['name' => 'Abigail', 'state' => 'CA'])
->withCallback($request->input('callback'));
from the official doc https://laravel.com/docs/5.4/responses#json-responses
And maybe try to make your validation in your model directly
class User extends Eloquent
{
private $rules = array(
'fullName' => 'required|max:255',
'email' => 'required|email',
'phone' => 'required|numeric'
);
public function validate($data)
{
// make a new validator object
$v = Validator::make($data, $this->rules);
// return the result
return $v->passes();
}
}
and in your controller you can make
$new = Input::all();
$u = new User();
if ($b->validate($new))
{
}
else
{
}
In my laravel project I am checking for status and verified_email after login.but shows the error for username password not match only do not checking the error code which is going after login and loading the page continuously.
sessioncontroller
<?php
namespace App\Http\Controllers;
use Request;
use Response;
//----models--------
use App\Site;
use App\Jobs;
use Auth;
use DB;
use Validator;
use Redirect;
use Illuminate\Support\MessageBag;
class SessionController extends Controller {
public function index(){
return Redirect::to('login');
}
public function store()
{
$input = Request::only('username', 'email', 'password');
$credentials = [
'username' => Request::get('username'),
'password' => Request::get('password')
];
if (!Auth::attempt($credentials))
{
return Redirect::back()->with('alert-danger', 'Username or password do not match.');
}
else
{
if (Auth::user()->verified_email != 1) {
Auth::logout();
return Redirect::back()->with('alert-danger', 'Please verify your email.');
}
if (Auth::user()->status != 'A') {
Auth::logout();
return Redirect::back()->with('alert-danger', 'Your Account is disabled.Please contact your Administrator.');
}
$credentials_last_login = [
'last_login_at' => '',
'username' => array_get('username', $input, ' '),
'password' => array_get('password', $input, ' ')
];
if (Auth::attempt($credentials_last_login))
{
return redirect('/change_password');
}
else
{
return redirect('/properties');
}
}
}
}
It gives an error alert when username password not match but do not when verified_email is not 1 and when status is not Active instead of showing the error just load it.
Your password is being stored as a hash but I think your calling it plain - try:
'password' => Hash::make($request->password)