verify controller in sms register - laravel

I created a website with Register SMS functionality that the contact was sent for to him when registering an identity code and he is also stored in the file name table.
Now what do I need to do to controllerverify until user the contact with his code and activate his account?

code verifyControlller ::
public function activeUser(Request $request, $phone)
{
$code = $request->code;
$user = User::where('phone', $phone)->whereHas('activitionCode', function ($query , $request) {
$query->where('code', $request->code)->where('expire', '<', Carbon::now());
})->first();
if ($user) {
$user->active = 1;
$user->save();
} else {
return back()->withErrors(['code', 'code invalide']);
}
}
}

Related

Laravel - How to map route with logged in user based on organization

In my Laravel-5.8 I am developing multi-organization application without using any package. Also I am using Azure Socialite Login.
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/dashboard';
protected $username = 'username';
public function redirectToProvider()
{
return Socialite::with('azure')->redirect();
}
public function handleProviderCallback()
{
$azureUser = Socialite::with('azure')->user();
try
{
$user = User::where('email', $azureUser->email)->orWhere('username', $azureUser->user['mailNickname'])->first();
if($user)
{
if(Auth::loginUsingId($user->id))
{
$user->update([
'last_login_at' => now(),
]);
return redirect()->intended('/dashboard');
}
}
}
catch(\Exception $e)
{
session()->flash("error", "Authentication failed, kindly contact the Administrator!");
return redirect(route('login'));
}
}
}
I have these models:
class Organization extends Model
{
protected $table = 'organizations';
protected $fillable = [
'id',
'org_name',
'subdomain',
];
}
class User extends Authenticatable
{
protected $fillable = [
'name',
'username',
'email',
'password',
'organization_id',
];
public function organization()
{
return $this->belongsTo('App\Models\Organization');
}
}
I have created a middleware so that I map the route with the organization subdomain.
class ConfirmDomain
{
public function handle($request, Closure $next)
{
$domain == "laraapp";
$path = $request->getPathInfo(); // should return /laraapp.net or /organization1.laraapp.net
if (strpos($path, ".") !== false) { // if path has dot.
list($subdomain, $main) = explode('.', $path);
if(strcmp($domain, $main) !== 0){
abort(404);
}
} else{
if(strcmp($domain, $path) !== 0){
abort(404); // if domain is not myapp then throw 404 page error
}
$subdomain = ""; // considering for main domain value is empty string.
}
$org = OrgCompany::where('subdomain', $subdomain)->firstOrFail(); // if not found then will throw 404
$request->session()->put('subdomain', $org); //store it in session
return $next($request);
}
}
Organization table
id | org_name | subdomain
1 | Main |
2 | Organization1 | organization1
I want to add main-domain(https://laraapp.net) and sub-domains (https://organization1.laraapp.net) where each will see the data based on the organization_id in each table
https://laraapp.net
https://organization1.laraapp.net
A user can exit in more that one organization.
When a user logins in with azure socialite, I want the application to check the domain and sub-domain route and use it to get the organization_id, then map it with the organization_id in the user tables.
For instance, if user logs in using https://laraapp.net, the application use it to get the organization_id in the user table, and if it is https://organization1.laraapp.net, it does likewise and so on.
The user should only see the profile based on his organization. Also should only see it's organization data.
How do I achieve this from the route and LoginController?

Laravel 7: custom guard authentication does not work as expected

I have a multiauth project. I have the default authentication and a custom guard. At the login controller, when I make the login attempt, it authenticates as expected. However, when it gets to the homepage, the custom guard is not logged in anymore.
Users that use the custom guard already log in through an external API, so i don't want them on my users table. I just need a couple of fields to show them some content.
LoginController.php (Up to the return, attempt method returns TRUE)
...irrelevant code...
Auth::guard('ivao')->attempt(array('vid' => $user_array->vid, 'name' => $user_array->name, 'surname' => $user_array->surname), true);
Cookie::queue(Cookie::forever($this->cookie_name, $_COOKIE['ivao_token']));
Cookie::queue(Cookie::forever('vid', $user_array->vid));
return redirect('/');
...irrelevant code...
CustomProvider.php
class CustomUserProvider extends ServiceProvider implements UserProvider
{
public function retrieveById($identifier)
{
}
public function retrieveByToken($identifier, $token)
{
if(Cookie::get('rememberToken') == $token)
{
$user = new ApiUser();
$user->vid = Cookie::get('vid');
$user->name = Cookie::get('name');
$user->surname = Cookie::get('surname');
return $user;
}
else return NULL;
}
public function updateRememberToken(UserContract $user, $token)
{
if(Cookie::get('rememberToken') == $token)
{
Cookie::queue(Cookie::forever('vid', $user->vid));
Cookie::queue(Cookie::forever('name', $user->name));
Cookie::queue(Cookie::forever('surname', $user->surname));
Cookie::queue(Cookie::forever('rememberToken'), $token);
return TRUE;
}
else return FALSE;
}
public function retrieveByCredentials(array $credentials)
{
$user = new ApiUser();
$user->vid = $credentials['vid'];
$user->name = $credentials['name'];
$user->surname = $credentials['surname'];
return $user;
}
public function validateCredentials(UserContract $user, array $credentials)
{
return TRUE; //already validated at the API
}
}
Homepage Controller (Here both check methods return FALSE)
class PagesController extends Controller
{
public function index($folder= '', $page= 'inicio')
{
if( !(Auth::check() || Auth::guard('ivao')->check()) ) return redirect('/login');
...irrelevant code...
Please let me know if you need further information. Hope someone can help. I'm stuck. Thanks.

How to check auth login 3 table laravel?

i have a auth login that i make, which have 3 table to auth as admin, how can i fix this? thx
public function postlogin(Request $request)
{
$admin = DB::table('M_ADMIN')->select(['M_ADMIN.PERNR'])->get();
$user = DB::table('M_HEAD_SALLARY')
->join('M_USER', 'M_USER.PERNR', '=', 'M_HEAD_SALLARY.PERNR')
->where('M_USER.PERNR','LIKE','%'.$admin.'%')
->where('M_HEAD_SALLARY.USRID_LONG',strtoupper($request->USRID_LONG))
->where('M_USER.PASS',$request->PASS)
->first();
return redirect('/login');
}
In your LoginController, you can overwrite the attemptLogin method as follow
public function attemptLogin(Request $request) {
$user = Admin::whereHas('M_HEAD_SALLARY', function($query){
// condition
})->whereHas('M_USER', function($query) {
// condition
});
if (Auth::login($user)) {
// Authentication passed...
}
}

How add new parameter to check in login Laravel

In LoginController I override the credentials method, like this:
protected function credentials(Request $request)
{
$credentials = $request->only($this->username(), 'password');
$credentials['status'] = User::STATUS_ACTIVE;
return $credentials;
}
And this work pretty fine. But when a try to add a parameter which is not a column of the Users table I don't know how to check there. Some like this:
protected function credentials(Request $request)
{
$credentials = $request->only($this->username(), 'password');
$credentials['status'] = User::STATUS_ACTIVE;
$credentials['customer-status'] = Customer::STATUS_ACTIVE;
return $credentials;
}
Where can I check if the value is correct? I tried to make an event listener to attempt login, but it doesn't work. My idea is to make an Eloquent query to return an account of customers activities. If more then one, customer-status for this user is true.
If anyone is interested in knowing how I solved it, the explanation is as follows:
Based on this code I found in github: https://gist.github.com/joseluisq/fb84779ea54eaebf54a9d8367117463e
In LoginController.php I override 2 methods(login and sendFailedLoginResponse):
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$this->incrementLoginAttempts($request);
$user = User::where('email', $request->email)->first();
if (!$user) {
return $this->sendFailedLoginResponse($request);
}
$customers = Customer::join('users_customers', 'users_customers.customer_id', 'customers.id')
->where([
['users_customers.user_id', '=', $user->id],
['customers.status', '=', Customer::STATUS_ACTIVE]
])
->count();
if ($customers === 0) {
return $this->sendFailedLoginResponse($request, 'auth.inactive');
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
return $this->sendFailedLoginResponse($request);
}
protected function sendFailedLoginResponse(Request $request, $trans = 'auth.failed')
{
$errors = ['email' => trans($trans)];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()
->back()
->withErrors($errors);
}
Remember yourself to define message on auth.php and set uses needed.
Ps.: I don't use $credentials['customer-status'] = Customer::STATUS_ACTIVE;,
as I thought I would.

Switching user in laravel 5.4

I am switching users in laravel and I succeeded in that as well but the thing is when I redirect the user to the dashboard after successful login it redirects to login form instead I don't know what am I doing wrong. Here is the code I am using.
public function user_reauthenticate(Request $request) {
$input = Input::all();
$data = User::where('email', $input['email'])->first();
if ($data) {
if (Hash::check($input['password'], $data->password)) {
Session::put('email', $input['email']);
$newuser = Student::find($input['new_user']);
session(['orig_user' => $data->id]);
Auth::login($newuser);
return Redirect::back();
} else {
$response = 'Wrong Credentials';
}
} else {
$response = 'User does not exist';
}
}
Can anyone help me find out the issue?
Edited
You can log in with
Auth::loginUsingId(1);
New edited
// If you have the guard student and multiple auth
$auth = auth()->guard('student');
$objAuth = $auth->loginUsingId($input['new_user']);
//Single Auth
$objAuth = Auth::loginUsingId($input['new_user']);
Add this to your top of the file:- use Illuminate\Foundation\Auth\AuthenticatesUsers;
Afterwards add a if function like below in your already completed code:-
public function user_reauthenticate(Request $request)
{
use AuthenticatesUsers;
$input = Input::all();
$data = User::where('email', $input['email'])->first();
if ($data) {
if (Hash::check($input['password'], $data->password))
{
Session::put('email', $input['email']);
$newuser = Student::find($input['new_user']);
session(['orig_user' => $data->id]);
Auth::login($newuser);
if ($this->attemptLogin($request))
{
return $this->sendLoginResponse($request);
}
}
else
{
$response = 'Wrong Credentials';
}
}
else
{
$response = 'User does not exist';
}
}
After this method override this method as follows:-
protected function authenticated(Request $request, $user)
{
return redirect()->route('dashboard');
}
Check whether your dashboard route is named dashboard or if not name it.

Resources