Laravel login without register - laravel

Is it possible to login a user in Laravel 7 without having the user on the database? I have a group of users, which I don't want them on my database, because they use an external API to do the login and I can get their details from that API (via XML).
There are 3 types of users:
AR division users. Normal registered users.
Non-AR division users, but $user->gca = 1. Registered users too.
Non-AR division and Non-GCA users. Non-registered users.
All of them use an external API for the login. However, I only register the first 2 ones on my database for organisational purposes.
My intention is to use Laravel login using the 3rd type user details from the API without touching my database.
My code at LoginController.php
$user_array = json_decode(file_get_contents($this->api_url . '?type=json&token=' . $request->cookie($this->cookie_name)));
if ($user_array->result)
{
$u = NULL;
if ($user = User::find($user_array->vid)) $u = $user;
else if($user_array->division == 'AR' || !is_null(Gca::find($user_array->vid)))
{
$u = new User();
if(! is_null(Gca::find($user_array->vid))) $u->gca = 1;
$u->name = $user_array->firstname;
$u->vid = $user_array->vid;
$vid = $u->vid;
$u->save();
return view('register', compact('vid'));
}
else
{
$user = new User();
$user->division = $user_array->division;
$user->vid = $user_array->vid;
$user->name = $user_array->firstname;
$user->surname = $user_array->lastname;
Auth::login($user); //This doesn't seem to work.
return redirect('/');
}
}
Thanks.

Related

Laravel - Check if user is authenticated on another server

Let say I have a laravel site on a host and another host just for storing some specific files. In second host I want to check if user is authenticated on laravel site and then I gave him/her access to the file. How can I do this?
You could pretty much just use normal PHP code for that, without having to touch the Laravel framework on your other server.
For example, create your own custom cookie or session variable that contains a token from authentication. Make the logic something like $authToken = md5($user->username) . "." . md5($user->password);, then just add it to a cookie or the $_SESSION[] variable.
From here, create a small backend on the other server that you use for storage, and do something like this.
<?php
/////////////
/**
* Here there should be database connection logic.
*/
/////////////
$posts = (object) $_POST;
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$postArray = [
'authToken',
'user'
];
foreach($postArray as $post)
{
if (!isset($_POST[$post]))
{
return false;
}
}
$query = htmlspecialchars("SELECT * FROM users WHERE id=" . $posts->user);
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_all($result);
$db_stack = md5($row['username']) . "." . md5($row['password']);
if ($posts->authToken != $db_stack)
{
return false;
}
// Return the requested file here.
}
If (Auth::check()) $file = file_get_contents($urlToFile);

Can I give my user a choice to choose his own subdomain in Laravel project?

I have implemented multi-tenancy in a project with unique subdomains & separate dbs. Now, my client said that we will provide subdomain of customer’s choice. In this way, duplication is obvious. The flow is like this:
If two users have this one domain (user1 => http://user.abc.com & user2 => http://user.abc.com ), then how can I determine who is who? The main problem is, I am going to register the user myself, there is no registration process for the customer, so, customer will provide his domain to us manually for example: he likes to have his domain “user” and if I would have “user” already in my database, how can I provide the same hostname to my another customer. Won’t it seems strange that we are calling our customer back and telling them that we have already this hostname please give us another name of your choice. Yes, all this makes sense when we would have been giving the registration process to our customer and there he can enter hostname of his own choice like we enter our email addresses on gmail, hotmail and etc. Please tell me if I am going in wrong direction.
Here is my code:
routes/web.php
Route::group(['middleware' => 'subdomain'], function () {
Route::get('/sales', 'HomeController#index');
Route::get('/sales/register', 'HomeController#register');
});
Middleware/SubDomainAccess.php
public function handle($request, Closure $next)
{
$server = explode('.', $request->server('HTTP_HOST'));
$subdomain = $server[0];
$config = array();
if($subdomain == "myapp"){
$defaultSite = SuperAdminModel::where('db_name', 'main_db)->first();
$config['id'] = $defaultSite["admin_id"];
$config['site_url'] = $defaultSite["site_url"];
$config['host'] = "localhost";
$config['db_name'] = "main_db";
$config['user'] = "my_user";
$config['password'] = "mypassword";
$request->attributes->add(['myAttribute' => "SUPER ADMIN"]);
}
else{
$site = TenantModel::where('tenant_hostname', $subdomain)->first();
if(!is_null($site)){
$config['id'] = $site["id"];
$config['tenant_domain'] = $site["tenant_domain"];
$config['tenant_hostname'] = $site["tenant_hostname"];
$config['db_name'] = "mysite_".$site["id"]."_".$site["tenant_hostname"]."_db";
$config['user'] = "my_user";
$config['password'] = "mypassword";
$config['host'] = "localhost";
$request->attributes->add(['myAttribute' => $site['tenant_company_name']]);
}else{
return abort(404);
}
}
\Config::set('database.connections.mysql.host', $config['host'] );
\Config::set('database.connections.mysql.database', $config['db_name'] );
\Config::set('database.connections.mysql.username', $config['user']);
\Config::set('database.connections.mysql.password', $config['password']);
\DB::reconnect();
return $next($request);
}
If more details are required to understand the code, I will provide it.
Thank you

Yii2. Authorised users list

I've used standard yii2 functions for authorization. User sessions are stored in database.
How can I get the list of all authorized users in Yii2?
Use this code:
$sessions = (new Query())->select('*')->from('session')->where('expire > :now', [
':now' => time()
])->all();
foreach($sessions as $session) {
$sessionData = Yii::$app->session->readSession($session['id']);
$sessionUnserializedData = $this->unserialize_session($sessionData);
$userId = $sessionUnserializedData['__id'];
echo $userId;
}
unserialize_session method get from #phred gist.

Symfony2 rest and oauth, can't persist session

I'm using FosRestBundle and FosOauthServerBundle for an api with Symfony.
I have a route /login/username/password, in this action i loggin the user manually :
$encoder_service = $this->get('security.encoder_factory');
$encoder = $encoder_service->getEncoder($user);
$encoded_pass = $encoder->encodePassword($password, $user->getSalt());
if ($user->getPassword() == $encoded_pass) {
$token = new UsernamePasswordToken($user, $password, "api", $user->getRoles());
$this->get("security.context")->setToken($token);
$event = new InteractiveLoginEvent($this->get("request"), $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
}
If i check in my database after that (i save session in my database) i have a new line, and at the end of my action, if i check $this->getUser() i have the good one.
But after that, in another action, if i check $this->getUser() i have noting... I can't retrieve a user session from an action to another.
Do you have any ideas ?
Ediy: If i check $this->container->get('security.context')->getToken()i have :
{"roles":[{"role":"ROLE_USER"}],"authenticated":true,"attributes":[],"token":"MYTOKEN"}
But i haven't my user..
You should be able to fetch your user from security context. I usually define this as a separate function in the controllers where i need it :
public function getConnectedUser()
{
$user = null;
if ($this->get('session')->has('_security_member') && !is_null($this->get('security.context')->getToken())) {
$user = $this->get('security.context')->getToken()->getUser();
}
return $user;
}
You can then access it from every action of your controller.
$user = $this->getConnectedUser();

laravel login with google account

I am making an application and I want users to login with their google account. I have user oauth-4-laravel and I have this:
UserController.php
// get data from input
$code = Input::get('code');
// get google service
$googleService = Artdarek\OAuth\Facade\OAuth::consumer("Google");
if (!empty($code)) {
// This was a callback request from google, get the token
$token = $googleService->requestAccessToken($code);
// Send a request with it
$result = json_decode($googleService->request('https://www.googleapis.com/oauth2/v1/userinfo'), true);
$user = DB::select('select id from users where email = ?', array($result['email']));
if (empty($user)) {
$data = new User;
$data->Username = $result['name'];
$data->email = $result['email'];
$data->first_name = $result['given_name'];
$data->last_name = $result['family_name'];
$data->save();
}
if (Auth::attempt(array('email' => $result['email']))) {
return Redirect::to('/');
} else {
echo 'error';
}
}
// if not ask for permission first
else {
// get googleService authorization
$url = $googleService->getAuthorizationUri();
// return to facebook login url
return Redirect::to((string) $url);
}
}
After this i get successfully user info and can save user name, in my database. The problem is that after this I want to redirect user to home page and can't do this because with normal login i chec authentication:
if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')))) {
return Response::json(["redirect_to" => "/"]);
and with google login i get onlu username , user id and email. How to login directly the user after google login?
If you need to log an existing user instance into your application, you may simply call the login method with the instance:
$user = User::find(1);
Auth::login($user);
This is equivalent to logging in a user via credentials using the attempt method.
For further info see: http://laravel.com/docs/security#manually

Resources