Drupal 7 session handling - drupal-7

I am trying to login into Drupal from a remote site using the REST api method. I need to get the session ID for the authenticated user from Drupal. I am using Drupal 7.
Please help

Here, I defined to create session to store ID for the authenticated user at login and registration time.
/*
* At Login time to create session to store user id.
*
* Implement hook_user_login()
*/
function module_user_login(&$edit, $account) {
session_start();
$_SESSION['user_id'] = $account->uid;
}
/*
* At Registration time to create session to store user id.
*
* Implement hook_user_insert()
*/
function module_user_insert(&$edit, $account, $category) {
session_start();
$_SESSION['user_id'] = $account->uid;
}

Related

How to deal with External authentication for already existing local user or new user

I using ASP.Net Core 3 Identity with Identity Server 4 for authentication ...
On the AspNetIdentity template the External Authentication Controller Callback method calls the AutoProvisionUserAsync method which has the following code:
var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;
if (email != null) {
filtered.Add(new Claim(JwtClaimTypes.Email, email));
}
var user = new User {
UserName = Guid.NewGuid().ToString(),
};
var identityResult = await _userManager.CreateAsync(user);
Basically it creates a user with a Guid as Username ...
In my database I am using Email as Username ... Is there any reason to use a Guid?
I suppose most External authentication services (Google, Facebook, etc) provides an Email.
So my idea would be:
Check if there is an User in the database already with that email.
If no User exists create one with the email obtained from the External authentication service.
Also add the external authentication to the User in the database;
If there is a User with the email in the database check if it has that External Login.
If the user does not have the external login register and add it.
Does this make sense?
Check if there is an User in the database already with that email.
On callback, first call is to FindUserFromExternalProviderAsync, it search users using nameIdentifier, then if not found there is call to AutoProvisionUserAsync
Basically it creates a user with a Guid as Username ...
In my database I am using Email as Username ... Is there any reason to use a Guid?
The ApplicationUser's base class is IdentityUser, IdentityUser has a prop for ID and one for email by design. thats why most of libraries take advantage of having GUID as ID in addition of email for extensibility. You can use the email for ID if you like to.

Authenticating guest/anonymous users using JWT

I'm building an SPA that a user can upload some files. The front-end is written in AngularJS while the back-end is using an API in Laravel 5.7. The authentication is implemented using the jwt-auth library.
So far I have implemented this for registered users where each user has a personal directory on the server where he/she uploads the files. The difference between the registered and the anonymous users is that the files of the anonymous will be deleted after a while.
Now, I want to do the same for anonymous/guest users (if the press the button continue as a guest). So what I tried first in the authContrroller.php side is to use something like this:
public function authentication(Request $rrequest) {
$credentials = $request->only('email', 'password');
// Guest authentication
if( $credentials['email'] === 'guest' && $credentials['password'] === 'guest' )
{
$payload = auth()->factory()->claims(['sub' => $this->createRandomDir()])->make();
$token = auth()->manager()->encode($payload);
// OR
$factory = JWTFactory::customClaims([
'sub' => $this->createRandomDir(),
]);
$payload = $factory->make();
$token = JWTAuth::encode($payload);
}
// Registered user authentication authentication
else
{
if (! $token = auth()->setTTL(60)->attempt($credentials))
return response()->json(['error' => 'invalid_credentials'], 400);
}
return response()->json(compact('token'));
}
The idea was to create a random directory and enclose it inside the payload and use it on the next requests.
But in the case of the guest, the server returns as a token an empty object. Possibly because there wasn't a user in the DB.
Another idea that I'm thinking of is to create a random user (add it to the DB) and assign to it a random directory each time a user needs to use the app as guest/anonymous. The only thing that I'm afraid on that approach is that if there are thousands of guests then thousands random users should be created on the DB.
So what do you think? Is there any other and more efficient way to handle this?
Any idea is welcomed.

CakePHP 3: How to automatically log a user in after registration

I am trying to log a user in using CakePHP 3 right after registration, but I have not been successful. This is what I am doing:
function register(){
// ....
if($result = $this->Users->save($user)){
// Retrieves corresponding user that was just saved
$authUser = $this->Users->get($result->id);
// Log user in using Auth
$this->Auth->setUser($authUser);
// Redirect user
$this->redirect('/users/account');
}
}
I guess posting this question opened my eyes to a fix. This is what I did to get it to work... if there is better way, I would be glad to change it...
function register(){
// .... Default CakePHP generated code
if($result = $this->Users->save($user)){
// Retrieve user from DB
$authUser = $this->Users->get($result->id)->toArray();
// Log user in using Auth
$this->Auth->setUser($authUser);
// Redirect user
$this->redirect(['action' => 'account']);
}
}
CakePHP 3.8 × cakephp/authentication update.
Any place you were calling AuthComponent::setUser(), you should now use setIdentity():
// Assume you need to read a user by access token
$user = $this->Users->find('byToken', ['token' => $token])->first();
// Persist the user into configured authenticators.
$this->Authentication->setIdentity($user);
Source: /authentication/1/en/migration-from-the-authcomponent.html#checking-identities

GAE Cloud Endpoint not showing 401 auth error

I am trying to use authentication to save profile but GAE Endpoint does not give 401 error even if user is null.
Instead Endpoint is responding with 200 ok and giving default results.
BTW this is part of the Udacity Course.
/**
* Creates or updates a Profile object associated with the given user
* object.
*
* #param user
* A User object injected by the cloud endpoints.
* #param profileForm
* A ProfileForm object sent from the client form.
* #return Profile object just created.
* #throws UnauthorizedException
* when the User object is null.
*/
// Declare this method as a method available externally through Endpoints
#ApiMethod(name = "saveProfile", path = "profile", httpMethod = HttpMethod.POST)
// The request that invokes this method should provide data that
// conforms to the fields defined in ProfileForm
// TODO 1 Pass the ProfileForm parameter
// TODO 2 Pass the User parameter
public Profile saveProfile(final User user) throws UnauthorizedException {
String userId = null;
String mainEmail = null;
String displayName = "Your name will go here";
TeeShirtSize teeShirtSize = TeeShirtSize.NOT_SPECIFIED;
// TODO 2
// If the user is not logged in, throw an UnauthorizedException
if(user== null){
throw new UnauthorizedException("Authorization Required!");
}
// TODO 1
// Set the teeShirtSize to the value sent by the ProfileForm, if sent
// otherwise leave it as the default value
// TODO 1
// Set the displayName to the value sent by the ProfileForm, if sent
// otherwise set it to null
// TODO 2
// Get the userId and mainEmail
// TODO 2
// If the displayName is null, set it to default value based on the user's email
// by calling extractDefaultDisplayNameFromEmail(...)
// Create a new Profile entity from the
// userId, displayName, mainEmail and teeShirtSize
Profile profile = new Profile(userId, displayName, mainEmail, teeShirtSize);
// TODO 3 (In Lesson 3)
// Save the Profile entity in the datastore
// Return the profile
return profile;
}
Unfortunately its a known issue. Go "Star" this issue to get updates on when it's fixed. There are a couple workarounds in the first link, heres a quote from it:
There are two workarounds (1) save the user and read back from the
store, if it refers to a valid account the user id will be populated
(this sucks because you pay the saving / loading / deletion cost for
each API access that is authenticated even if it is tiny, and
obviously some performance cost) and (2) you could use the google+ ID
but that is NOT the same as the user id.

How to count login attempts in CakePHP

I'm developing application with CakePHP 1.3 and using its Auth component. Is it possible to count login fails in order to deactivate users account after a few unsuccessfull attempts? Is there anything like loginErrorRedirect?
How are you intending to deactivate a user if they can't login? If they login as
test#test.com FAIL
tester#test.com FAIL
test123#test.com FAIL
are you going to invalidate all these users?
To record login failures, your could add the following to your login() action in whatever controller
if(empty($this->Session->Auth) && isset($this->data))
{
if($this->Session->read('login.fail'))
{
$login_fail = $this->Session->read('login.fail') + 1;
}else{
$login_fail = 1;
}
$this->Session->write("login.fail",$login_fail);
}

Resources