Auth session is unset after auth then the application redirect


#1

After authentication, I set auth session via auth.loginViaId(1) then redirect to another route. But the controller of the route saying user not yet log in.

Authcontroller.js

await auth.loginViaId(1)
console.log('logged in user', await auth.getUser()) //logging authenticated user 
return response.redirect('/')

Homecontroller.js

try {
      console.log(await auth.getUser())
} catch (error) {
      console.log('You are not logged in')
}

HomeController is saying “you are not logged in”

Please help @virk @romain.lanz


#2

Can u share config/session.js file?


#3

@virk sure.

'use strict'

const Env = use('Env')

module.exports = {
  /*
  |--------------------------------------------------------------------------
  | Session Driver
  |--------------------------------------------------------------------------
  |
  | The session driver to be used for storing session values. It can be
  | cookie, file or redis.
  |
  | For `redis` driver, make sure to install and register `@adonisjs/redis`
  |
  */
  driver: Env.get('SESSION_DRIVER', 'cookie'),

  /*
  |--------------------------------------------------------------------------
  | Cookie Name
  |--------------------------------------------------------------------------
  |
  | The name of the cookie to be used for saving session id. Session ids
  | are signed and encrypted.
  |
  */
  cookieName: 'adonis-session',

  /*
  |--------------------------------------------------------------------------
  | Clear session when browser closes
  |--------------------------------------------------------------------------
  |
  | If this value is true, the session cookie will be temporary and will be
  | removed when browser closes.
  |
  */
  clearWithBrowser: true,

  /*
  |--------------------------------------------------------------------------
  | Session age
  |--------------------------------------------------------------------------
  |
  | This value is only used when `clearWithBrowser` is set to false. The
  | age must be a valid https://npmjs.org/package/ms string or should
  | be in milliseconds.
  |
  | Valid values are:
  |  '2h', '10d', '5y', '2.5 hrs'
  |
  */
  age: '2h',

  /*
  |--------------------------------------------------------------------------
  | Cookie options
  |--------------------------------------------------------------------------
  |
  | Cookie options defines the options to be used for setting up session
  | cookie
  |
  */
  cookie: {
    httpOnly: true,
    sameSite: true,
    path: '/'
  },

  /*
  |--------------------------------------------------------------------------
  | Sessions location
  |--------------------------------------------------------------------------
  |
  | If driver is set to file, we need to define the relative location from
  | the temporary path or absolute url to any location.
  |
  */
  file: {
    location: 'sessions'
  },

  /*
  |--------------------------------------------------------------------------
  | Redis config
  |--------------------------------------------------------------------------
  |
  | The configuration for the redis driver. By default we reference it from
  | the redis file. But you are free to define an object here too.
  |
  */
  redis: 'self::redis.default'
}


#4

Can u log the error, instead of logging a static message


#5

@virk I think, i should give you details. Trying to login via social authentication adonis-ally

AuthController.js

const provider = params.provider
    try {
      const providerUser = await ally.driver(provider).getUser()
        const userDatat = providerUser
        const user_ = new User()
        user_.name = userData.getName()
        user_.username = userData.getNickname()
        user_.avatar = userData.getAvatar()
        user_.email = userData.getEmail()
        await user_.save()

        const profile = new UsersProfile()
        profile.provider = provider
        profile.provider_id = userData.getId()
        profile.oauth_token = userData.getAccessToken()
        profile.oauth_token_secret = userData.getTokenSecret()
        await user_.profile().save(profile)
        await auth.loginViaId(user_.id)
        // return view.render('welcome')
        return response.redirect('/')
    } catch (e) {
      console.log(e)
    }

if I log in via Facebook, GitHub, Instagram, and linkedin. The session will work fine and no issue. But if I log in via twitter and google, HomeController.js will say “You are not logged in” but if use other social authentication to log in, It will work fine.

Hope you understand.


#6

I don’t think that the social driver will impact the login flow in any way, since you just call the loginViaId method and it has nothing to do where the id came from.

Can u add more logging to your and app, whether or not you are passing the right data to loginViaId or not?


#7

by google make sure you have enabled Google+ API

https://console.developers.google.com/apis
Google+ API > Enable

you did not provide a clear logging infos so it is my guess that your response is not correct


#8

If you copy paste that part from your Authcontroller.js

the issue might be the superfluous t in userDatat?


#9

@virk I agree with you on this one. So I needed more logs to my application

AuthController.js

const provider = params.provider
    try {
      const providerUser = await ally.driver(provider).getUser()
        const userDatat = providerUser
        const user_ = new User()
        user_.name = userData.getName()
        user_.username = userData.getNickname()
        user_.avatar = userData.getAvatar()
        user_.email = userData.getEmail()
        await user_.save()

        const profile = new UsersProfile()
        profile.provider = provider
        profile.provider_id = userData.getId()
        profile.oauth_token = userData.getAccessToken()
        profile.oauth_token_secret = userData.getTokenSecret()
        await user_.profile().save(profile)
        await auth.loginViaId(user_.id)
        console.log(await auth.getUser()) // Add this log and it logged the current user authenticated 
        return response.redirect('/')
    } catch (e) {
      console.log(e)
    }

Homecontroller.js

try {
      console.log(await auth.getUser()) 
} catch (error) {
      console.log('You are not logged in') 
}

HomeController keep logging “you are not logged in” instead of current user authenticated

that means something happened during return response.redirect('/')

Hope you understand my explantation.


#10

Can u share the actual error u get inside the home controller? Just log the error message


#11

@virk sure.

@h.elturkey I have enabled Google+ API. Can you try to Integrate Twitter and Google Social login with AdonisJS 4.0?


#12

i tried google already, it works fine

can u print ur response in this way to ensure the response

const providerUser = await ally.driver(provider).getUser()
return providerUser;

or

console.log(providerUser);


#13

@h.elturkey I’m receiving providerUser response. Just do something for me, please.

Login in with google or twitter, save providerUser detail in a database, set auth via auth.loginviaid(http://dev.adonisjs.com/docs/4.0/authentication#_loginviaid_id) then redirect to another page and try to get the logged in user details via auth.getUser (http://dev.adonisjs.com/docs/4.0/authentication#_getuser).

When done, let me know how it goes.


#14

@iamraphson

gggss

it works fine


#15

Worth sharing a repo with the code we can use to reproduce the issue


#16

@virk sure

Authentication controller:
https://github.com/iamraphson/adonisjs-hackathon-starter/blob/v2/app/Controllers/Http/Auth/AuthController.js

User Service Class
https://github.com/iamraphson/adonisjs-hackathon-starter/blob/v2/app/Services/UserService.js


#17

@h.elturkey can you help me reproduce the issue from my repo

https://github.com/iamraphson/adonisjs-hackathon-starter/tree/v2


#18

Sure I’ll check it out tonight


#19

@virk any update please?


#20

So I tried it on Safari and Firefox and it works fine. The reason I tried it on these browsers is that chrome has some issues in setting cookies on multiple redirects.

https://bugs.chromium.org/p/chromium/issues/detail?id=150066

Lemme research more about it and see what is the best way to fix that