How to prevent users log in without mail confirmation?
The database set correct. When user confirms the registration by clicking the link in the received message, the value "confirmed" changes from 0(default) to 1. Of course boolean type. I need "else if" statement to work, but I can't figure out how. Here is my code:
public function postSignin(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
if (!Auth::attempt($request->only(['email', 'password']),
$request->has('remember')))
{
return redirect()->back()->with(notify()->flash("Ooops..", "error", [
'timer' => 5000,
'text' => 'Could not sign in with those details',
]));
}
else if ((Auth::attempt($request->only(['email', 'password'])))&&('confirmed'===0))
{
return redirect()->back()->with(notify()->flash("Ooops..", "error", [
'timer' => 5000,
'text' => 'Activate your account',
]));
}
else
{
return redirect()->route('home');
}
}
public function postSignin(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
// This line will always log the user **in** if the account is confirmed or not.
if (!Auth::attempt($request->only(['email', 'password']),
$request->has('remember')))
{
return redirect()->back()->with(notify()->flash("Ooops..", "error", [
'timer' => 5000,
'text' => 'Could not sign in with those details',
]));
}
else if (!Auth::attempt(["email"=>$request->input("email"),"password"=>$request->input('password'),"confirmation"=>1])
{
return redirect()->back()->with(notify()->flash("Ooops..", "error", [
'timer' => 5000,
'text' => 'Activate your account',
]));
}
else
{
return redirect()->route('home');
}
}
Related
I've been researching for all internet why do I get this error when I try to POST on the login api route:
Status 419
unknown status
Version HTTP/1.1
Transferred 6.94 KB (6.46 KB size)
Referrer Policy strict-origin-when-cross-origin
This is what I have on my UserController.php:
public function userSignUp(Request $request) {
$validator = Validator::make($request->all(), [
"name" => "required",
"email" => "required|email",
"password" => "required",
]);
if($validator->fails()) {
return response()->json(["status" => "failed", "message" => "validation_error", "errors" => $validator->errors()]);
}
$userDataArray = array(
"name" => $request->name,
"email" => $request->email,
"password" => md5($request->password),
);
$user_status = User::where("email", $request->email)->first();
if(!is_null($user_status)) {
return response()->json(["status" => "failed", "success" => false, "message" => "Ooops! Email ya registrado anteriormente"]);
}
$user = User::create($userDataArray);
if(!is_null($user)) {
return response()->json(["status" => $this->status_code, "success" => true, "message" => "Registro completado correctamente", "data" => $user]);
}
else {
return response()->json(["status" => "failed", "success" => false, "message" => "Fallo al registrar"]);
}
}
// ------------ [ User Login ] -------------------
public function userLogin(Request $request) {
$attr = $request->validate([
'email' => 'required|string|email|',
'password' => 'required|string|min:6'
]);
if (!Auth::attempt($attr)) {
return response()->json([
'message' => 'Invalid login details'
], 401);
}
$token = auth()->user()->createToken('auth_token')->plainTextToken;
$user = auth()->user();
$respon = [
'status' => 'success',
'msg' => 'Login successfully',
'content' => [
'status_code' => 200,
'access_token' => $token,
'token_type' => 'Bearer',
'user_name' => $user->name,
'user_email' => $user->email,
'user_id' => $user->id,
]
];
return response()->json($respon, 200);
}
And I have these routes on api.php:
Route::post("login", [UserController::class, "userLogin"]);
Route::post("register", [UserController::class, "userSignUp"]);
These routes works perfectly on the RESTED add-on on Firefox. This is on api.php, I shouldn't have any problem with csrf token.
When a new user get registered then it automatically logins, Which is working fine. I am hashing the password like this :
'$newUser->password = bcrypt($request->get('password'));'
It successfully hashes the password, My users table have password column which is varchar 255. And i have remember_token field too in users table. 'dd($request->all())' returns:
array:3 [
"email" => "info#hotmail.com"
"_token" => "QIwnHacApWg3SotAXtoCCMFNK3FYFoFBAv2LSx4c"
"password" => "adminadmin"
]
And, The email and password is 100% correct against the users table record.
The request is Ajax so i have the following code of JS:
$('.post-btn').click(function(){
$.ajax({
url: '/sign-in',
type: "post",
data: {'email':$('input[name=email]').val(), '_token': $('input[name=_token]').val(),'password': $('input[name=password]').val()},
success: function(data){
console.log(data);
window.location = '/';
}
});
});
The authenticate method :
public function authenticate(Request $request) {
$validator = Validator::make($request->all(),
[
'email' => "required",
'password' => 'required'
]
);
$user = array('email' => $request->get('email'),'password' => $request->get('password'));
if (Auth::attempt($user)) {
$response = array(
'status' => 'success',
'msg' => 'Successfully Logins.',
);
$user = new \App\User;
if(Auth::check()) {
}
return \Response::json($response);
} else {
$response = array(
'status' => 'failed',
'msg' => 'Invalid Credentials!',
);
return \Response::json($response);
}
}
The input field names are correct.
What else I am missing ?
This work for me:
public function authenticate(Request $request)
{
$validator = Validator::make($request->all(),
[
'email' => "required",
'password' => 'required'
]
);
$email = $request->input('email');
$password = $request->input('password');
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return \Response::json([
'status' => 'success',
'msg' => 'Successfully Logins.',
]);
}
else {
return \Response::json([
'status' => 'failed',
'msg' => 'Invalid Credentials!',
]);
}
}
Hope this will help you..
$user = array('email' => $request->email,'password' => $request->password);
I'm trying to make email optional when user signs up. Here is package. So I removed email' => 'required|email|unique:users', in this function:
public function signup(Request $request)
{
$credentials = $request->all();
$validator = Validator::make($credentials, [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:3'
]);
if ($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
try {
$user = $this->users->create($request->except('roles', 'permissions'));
if (!$user->id) {
return $this->response->error('could_not_create_user', 500);
}
$hasToReleaseToken = Config::get('boilerplate.signup_token_release');
if ($hasToReleaseToken) {
return $this->login($request);
}
return $this->response->created();
} catch (\Exception $e) {
return $this->response->error($e->getMessage(), 500);
}
}
then in config-boilerplate.php I also removed email:
'signup_fields_rules' => [
'name' => 'required',
'email' => 'required|email|unique:users',///// this
'password' => 'required|min:6'
],
But when I sign up I get this error :
"message": "Undefined index: email",
"status_code": 500,
"debug": {
"line": 173,
"file": "/Users/MyMac/Desktop/Project/laravel-5.3-boilerplate-api-jwt-vue2/vendor/dingo/api/src/Http/Response/Factory.php",
"class": "Symfony\Component\HttpKernel\Exception\HttpException",
the route:
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->post('auth/signup', 'App\Api\V1\Controllers\AuthController#signup');
Is there anything I need to disable to allow users sign-up with or without email ?
If you want to make email as optional field, just use sometimes|email See Docs. Try below code:
public function signup(Request $request)
{
$credentials = $request->all();
$validator = Validator::make($credentials, [
'name' => 'required',
'email' => 'sometimes|email',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:3'
]);
if ($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
try {
$user = $this->users->create($request->except('roles', 'permissions'));
if (!$user->id) {
return $this->response->error('could_not_create_user', 500);
}
$hasToReleaseToken = Config::get('boilerplate.signup_token_release');
if ($hasToReleaseToken) {
return $this->login($request);
}
return $this->response->created();
} catch (\Exception $e) {
return $this->response->error($e->getMessage(), 500);
}
}
config-boilerplate.php
'signup_fields_rules' => [
'name' => 'required',
'email' => 'sometimes|email',///// this
'password' => 'required|min:6'
],
I'm trying to figure out how to pass back to my ajax call that there were validation errors if there is so that I can prevent the page from continuing on and display those errors to the user.
/*
* Create User After they complete the first part of the form.
*
*/
public function createUserAndOrder(Request $request)
{
$validation = $this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|confirmed|unique:users,email',
'email_confirmation' => 'required'
]);
$credentials = [
'first_name' => $request->input('first_name'),
'last_name' => $request->input('last_name'),
'email' => $request->input('email'),
'password' => Hash::make(str_random(8)),
];
$user = Sentinel::registerAndActivate($credentials);
$user->role()->attach(5);
return response()->json([
'success' => true,
'errors' => null
]);
}
You can try it by using Validate Facade as:
$validator = \Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|confirmed|unique:users,email',
'email_confirmation' => 'required'
]);
// Validate the input and return correct response
if ($validator->fails())
{
return response()->json(array(
'success' => false,
'errors' => $validator->getMessageBag()->toArray()
), 422);
}
This would give you a JSON response like this:
{
'success': false,
'errors': {
'first_name': [
'The first name field is required.'
],
'last_name': [
'The last name field is required.'
]
}
}
My controller:
public function rules()
{
return [
[['text'], 'required', 'message' => 'Fill in this field'],
['text', 'string', 'min' => 6, 'message' => 'Too short message'],
['text', 'validateUser']
];
}
public function validateUser($attribute)
{
if (Yii::$app->user->isGuest)
$this->addError($attribute, 'You must be logged in');
}
I have 2 problems:
1) Instead of the message 'Too short message' i see 'text field should contain at least 6 characters.'
2) validateUser not added a warning 'You must be logged in'
Ad1. It should be ['text', 'string', 'min' => 6, 'tooShort' => 'Too short message'],
Ad2. Are you sure this condition is true? Can you use die() here or something like that? Or this validation rule isn't even activated?
For validateUser
public function rules()
{
return [
[['text'], 'required', 'message' => 'Fill in this field'],
['text', 'string', 'min' => 6, 'message' => 'Too short message'],
['text', 'required', 'when' => function($model){
return (Yii::$app->user->isGuest);
},'message'=>'You must be logged in'],
];
}