Giter Site home page Giter Site logo

cookie's People

Contributors

ajaxscape avatar aknuds1 avatar arb avatar arnivuo avatar augnin avatar bruderstein avatar chaseadamsio avatar cjihrig avatar devinivy avatar eladams avatar geek avatar geuis avatar gordysc avatar hofan41 avatar hueniverse avatar icehunter avatar jarrodyellets avatar jaw187 avatar lloydbenson avatar marsup avatar mrlannigan avatar mshick avatar mtharrison avatar nargonath avatar nlf avatar nwhitmont avatar paulovieira avatar paulwcy avatar pazzavlad avatar spridev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cookie's Issues

Unable to set cookie to browser session for a specific request

We have a default hapi-auth-cookie expiration of 2 weeks. However, for some users we want to allow them to set the auth cookie to be browser session only (e.g. unchecking a remember me checkbox on the login form).

e.g. plugin config

options: {
    password: process.env.AUTH_COOKIE_PWD,
    ttl: moment.duration(2, 'weeks').asMilliseconds(),
    domain: process.env.AUTH_COOKIE_DOMAIN,
    redirectUrl: '/login'
}

During the request we have something like this:

if(!remember) {
    request.auth.session.ttl(null);
}

However, this will still result in the ttl being set to moment.duration(2, 'weeks').asMilliseconds(),. It looks like statehood will always take the base options when the ttl is set to null: var definition = cookie.options ? Hoek.applyToDefaults(base, cookie.options) : base; (https://github.com/hapijs/statehood/blob/4fdaea4677c147e61175ad7ded4fa54dd1125dd7/lib/index.js#L354)

This makes sense from the statehood perspective, but from the hapi-auth-cookie perspective my expectation as a user would be that calling request.auth.session.ttl() would override the ttl set in default options - this only appears to be the case some of the time (for non-null values)

We can work around this on our side by defaulting everything to browser session and inverting our logic to explicitly set the ttl using this following:

if(remember === true) {
    request.auth.session.ttl(moment.duration(2, 'weeks').asMilliseconds());
}

However, this now means our main-line scenario (people leaving the box checked) has it's ttl separated from the hapi-auth-cookie plugin config.

Wanted to open this issue to see if there is a solution to have request.auth.session.ttl(null); work or if the hapi-auth-cookie docs should be updated to point out this scenario.

Typo in readme?

Very new to Hapi here, but it appears to me that the README should have s/server.pack.require/server.pack.register in the code example.

Update key in auth.credentials

Is there a way to update one key or add an additional key to auth.credentials without calling auth.session.set with a new object?

validateFunc doc

Hi,
got confused by following docs for validateFunc

credentials - a credentials object passed back to the application in request.auth.credentials. If value is null or undefined, defaults to session. If set, will override the current cookie as if request.auth.session.set() was called.

Because source code suggests that cookie just get updated by session object, not credentials object. And it gets updated only if keepAlive is true.

Expose 'path' in cookieOptions

Needing to host multiple HAPI applications under the same domain, but separated by resource path. Currently the module hardcodes the path to '/', and not having an option to change.

Unable to use environment variables to configure some scheme options

Currently, it is not possible to configure some of the options in this plugin using environment variables, since some of the options are assumed to be boolean/number types, while environment variables are strings.

I would like to request that this be made possible by using Joi's nifty validation() function which will accept a boolean/number string and return a transformed object with the appropriate types.

Pull request incoming.

Pass request object to validateFunc method?

Would it be possible to pass the request object to the validateFunc method? See my fork for a very trivial/slapdash implementation.

In my use case I'm writing a Hapi server that largely acts as a proxy to a different API. My validateFunc implementation includes a call out to this backing service to verify the user's auth token. The actual information I'm seeking to validate I'm storing in the session cookie (and thus get back as the first argument in validateFunc) but there's some other data in the request (like the user's IP address) that I'd like to forward on to the backing API for general logging/tracking purposes.

Is this a reasonable addition? Or is there some best practice I might be missing in my approach?

Current logged in user

I'm wondering how to use this so that on every request it will set my current authenticated user. Currently it seems that the only time request.auth.isAuthenticated is set is when I specifically set the route to require authentication. I'm trying to figure out how to get functionality like in rails or other frameworks where you always have access to the request.auth record without having to force them to be authenticated on each route. That way I can set a navbar header with the current logged in user on all pages. Does this make sense? Is there some other plugin I should be using for this?

Are there plans for Flash messages support?

Something similar to flash(type, message, isOverride) in Yar ? I think it's pretty common for websites to have the option to display some kind of one time messages 'error', 'success', 'warning' and it seem to have this wrapper method in the plugin for convenient use in request handlers. Or maybe there is better way to store one time sitewide messages?

how do I access the cookie after it is validated?

My code pretty much looks very similar to this repo.
https://github.com/santbob/hapi-auth-example

my request.auth object is

{ account:
   { provider: 'instagram',
     token: ' ',
     query: {},
     profile:
      { id: ' ',
        username: ' ',
        displayName: ' ',
        raw: [Object] } } }
{ isAuthenticated: true,
  credentials:
   { provider: 'instagram',
     token: ' ',
     query: {},
     profile:
      { id: ' ',
        username: ' ',
        displayName: ' ',
        raw: [Object] } },
  artifacts: { sid: ' ' },
  session: { set: [Function], clear: [Function], ttl: [Function] },
  mode: 'try',
  strategy: 'session' }

In one of my handlers, I tried

    if (request.auth.isAuthenticated)

and it did not pass.

How/where do I access the cookie so I can check if a user is authenticated in other parts of my app?

Clearing cookies

If we create a breaking change and want to clear the auth cookie for a user, how do you recommend doing that?

Should reply include unauthenticated error if `redirectOnTry = false` and mode is `try`?

I want auth to be optional, and simply return a slightly different page whether you have a session or not.

It seems like i should be able to set auth.mode to try and redirectOnTry = false and reply without passing the error through.

The unauthenticated error gets created here: https://github.com/spumko/hapi-auth-cookie/blob/master/lib/index.js#L81

Then included here: https://github.com/spumko/hapi-auth-cookie/blob/master/lib/index.js#L109

It replies properly but that exception shows up in logs even though it's not an exception .

Seems like maybe it shouldn't? Or am I doing it wrong.

I basically want optional auth without errors in either case.

domain is now required as a string, and null does not pass validation

Hapi's server.state accepts domain: null as an option, and this is a useful setting for me when in active development, because devs all use different local domains.

I think schema validation should be updated, and the logic here adapted to check property presence, not truthiness:

if (settings.hasOwnProperty('domain')) {
  cookieOptions.domain = settings.domain;
}

Bad cookie value even with clearInvalid true

Trying to use hapi-auth-cookie with a custom cookie name, validationFunc, and random password on each app restart seems to lead to "Bad cookie value" response anytime the app restarts. I thought clearInvalid would automatically clear the cookie, but it doesn't appear to.

Dirty sample below that shows basically what I'm doing without all the login/logout/etc... for clarity.

server.pack.register(Cookie, function (err){
  server.auth.strategy('auth', 'cookie', {
    password: config.password||uuid(),
    cookie: 'myapp',
    redirectTo: false,
    validateFunc: validate,
    isSecure: config.isSecure||false,
    clearInvalid: true
  });

  server.route([
    {
      method: 'GET',
      path: 'api/v1/test/auth',
      handler: function(req, reply){
        reply('Ok :)');
      },
      auth: 'auth'
    }
  ]);
});

Any pointers on where I'm going wrong?

Session Cookie is not being set via remote server

I have a thorax client app that is hosted on a static server. It needs to be accessible from various subdomains (foo.example.com, bar.example.com, baz.example.com). Each of the subdomains loads the same static files/thorax app.

I have a hapi.js app running on api.example.com with auth-cookie scheme in place.

My issue is having foo.example.com perform a login request and having api.example.com set the cookie for the session to be recognized on the server side in following request to protected endpoints.

If I make the request from foo.example.com to foo.example.com/login the cookie is set and the session works. However, this is not suitable for production. We need to have a static server serve up the thorax app and the hapi server manage sessions and endpoints.

I have CORS setup as such:

    cors: {
      matchOrigin: true,
      isOriginExposed: false,
      headers: ['Authorization', 'Content-Type', 'If-None-Match'],
      maxAge: Math.round(86400 * (365/12)),
      methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
    },

Any advice or help would be great appreciated!

Thanks.

`appendNext` no longer accepts a string

Received this error:

/Users/rockbot/npm-inc/newww/node_modules/hoek/lib/index.js:669
        throw arguments[1];
                       ^
ValidationError: child "appendNext" fails because ["appendNext" must be a boolean]
    at Object.exports.process (/Users/rockbot/npm-inc/newww/node_modules/hapi-auth-cookie/node_modules/joi/lib/errors.js:140:17)
    at internals.Any._validateWithOptions (/Users/rockbot/npm-inc/newww/node_modules/hapi-auth-cookie/node_modules/joi/lib/any.js:642:25)
    at root.validate (/Users/rockbot/npm-inc/newww/node_modules/hapi-auth-cookie/node_modules/joi/lib/index.js:102:23)
    at Object.internals.implementation [as cookie] (/Users/rockbot/npm-inc/newww/node_modules/hapi-auth-cookie/lib/index.js:41:23)
    at internals.Auth.strategy (/Users/rockbot/npm-inc/newww/node_modules/hapi/lib/auth.js:47:41)
    at internals.Plugin._applyChild (/Users/rockbot/npm-inc/newww/node_modules/hapi/lib/plugin.js:449:19)
    at Object.auth.strategy (/Users/rockbot/npm-inc/newww/node_modules/hapi/lib/plugin.js:61:65)
    at /Users/rockbot/npm-inc/newww/server.js:90:15
    at done (/Users/rockbot/npm-inc/newww/node_modules/hapi/node_modules/items/lib/index.js:30:25)
    at Object.exports.register (/Users/rockbot/npm-inc/newww/node_modules/hapi-auth-cookie/lib/index.js:15:5)
    at /Users/rockbot/npm-inc/newww/node_modules/hapi/lib/plugin.js:242:14
    at iterate (/Users/rockbot/npm-inc/newww/node_modules/hapi/node_modules/items/lib/index.js:35:13)
    at Object.exports.serial (/Users/rockbot/npm-inc/newww/node_modules/hapi/node_modules/items/lib/index.js:38:9)
    at internals.Plugin.register (/Users/rockbot/npm-inc/newww/node_modules/hapi/lib/plugin.js:224:11)
    at Object.<anonymous> (/Users/rockbot/npm-inc/newww/server.js:80:8)
    at Module._compile (module.js:456:26)

Here's the code that we've written (worked fine with version 2.0.0):

  server.auth.strategy('session', 'cookie', 'required', {
    password: process.env.SESSION_PASSWORD,
    appendNext: 'done',
    redirectTo: '/login',
    cookie: process.env.SESSION_COOKIE,
    clearInvalid: true,
    validateFunc: function (session, cb) {
      cache.get(session.sid, function (err, item, cached) {

        if (err) {
          return cb(err, false);
        }
        if (!cached) {
          return cb(null, false);
        }

        return cb(null, true, item);
      });
    }
  });

Sidenote: if this was a purposeful, breaking change, the community would expect the version to be bumped to 3.0.0, not 2.1.0.

Invalid cookie value

After not having started my server for a few hours, I receive the following error when I attempt to access a page with try as the mode: {"statusCode":400,"error":"Bad Request","message":"Invalid cookie value"}

I've looked at #34 which seems to say this is fixed/intended (not really sure which), however I do have "clearInvalid" set in my initialization, and the cookie password does not change.

# declare max valid time for session
sessionTime = 3 * 24 * 60 * 60 * 1000

# setup session cache
cache = server.cache({ cache:'sessionCache',segment: 'auth', expiresIn: sessionTime })

# Setup cookie based session authentication
server.register require("hapi-auth-cookie"), (err) ->
    if err?
        throw err

    server.auth.strategy 'session', 'cookie', true, 
        password: 'eetsacookies'
        ttl: sessionTime
        keepAlive: true
        cookie: 'sid'
        redirectTo: "/login"
        redirectOnTry: false
        clearInvalid: true
        isSecure: process.env.NODE_ENV isnt "development"
        validateFunc: (session, callback) ->
            cache.get session.sid, (err, cached) ->
                if err?
                    return callback(err, false)
                else if not cached?
                    return callback(null, false)
                else
                    Information.User.findById cached.userId, (err,user) ->
                        if err?
                            return callback( err,false)
                        else
                            return callback( null, true, user)

Any idea how I can have this error not appear? Is there a bug in my implementation or is this something with the library/hapi? Thanks in advance.

accessing auth, without fully blocking the endpoint

I would like to understand how to access auth to an end point even though its not required that one would have been authenticated, in a way, offer a different views according to authenticated users.
Simple example, /register if one is authenticated skip, if not show the form. My problem is if i use auth: 'stategy', everyone get redirected to /redirectURI with next register which is not what i want.

How to implement redirectUrl after authentication?

I'm actually using Bell and hapi-auth-cookie and I'm not sure which (or both) plugins would need to be involved since I don't quite understand yet how they interact, but I need to be able to send someone to a route to initiate auth and after they're successfully authenticated, redirect them to that URL.

It seems like this is a standard part of the OAUTH process, or at least once was, but I'm wondering if these plugins use that functionality and thus need to provide it themselves to effectively bring it back.

I'm trying to build a plugin to ease the use of bell and hapi-auth-cookie hapi-bell-cookie-auth-plugin, but just today I found another doing something similar https://github.com/hofan41/clapper and even more nicely written (though mine is very fresh in my defense).

I'm going to post this in Bell also and will close on either side if/when it's clear that it's a one-sided issue.

Redirect only when authenticated is required

I'm trying to figure out how I can redirect a user to /login?next=/protected only when authentication is required on a route.

For example, / should be public & accessible to anybody.
But when going to /protected & not logged in, you should be redirected to the route above.

I tried implementing this myself with onPreAuth but as I can't detect if a user is authenticated yet, it's not possible there. onPostAuth doesn't work either, as it has already redirected the request if it's not authenticated.

Sample password problem

Hi,

I've encountered a strange bug. I used the sample code passport 'worldofwalmart', now I'm trying to change it, but I'm constantly getting 400 "Bad cookie value: session". It doesn't matter which password I use. It only works 'worldofwalmart'.

My code:

yield server.pack.register require('hapi-auth-cookie')
  server.auth.strategy 'session', 'cookie',
    password: 'worldofwalmart'
    cookie: 'session'
    redirectTo: false
    isSecure: true
    ttl: 24* 60 * 60 * 1000

Working fine.

yield server.pack.register require('hapi-auth-cookie')
  server.auth.strategy 'session', 'cookie',
    password: <anything but 'worldofwalmart'>
    cookie: 'session'
    redirectTo: false
    isSecure: true
    ttl: 24* 60 * 60 * 1000

400 "Bad cookie value: session"

Do I have to clear some kind of cache or something?

Keep pathname or headers after redirectTo

So, my case:

If you access directly to an url which needs some auth and your aren't logged. I cannot get the refer url because I've been redirected. For example:

A. Access to domain.com/private
B. Because isn't logged it's redirected to domain.com/auth/signin
C. In the handlers now there's the data of /auth/signin not /private

I hope I've explained myself well enough. Maybe I'm thinking in a bad way and I shouldn't check the refer url like that, but this will be possible using Hapi? Or is planned? Or something?

Thanks

Build error

Hi.
the build is broken, can you please fix this ?

request.auth.credentials undefined after calling request.auth.session.set

I think this is more of a question than an issue. In my login page I'd like to perform the login, set the credentials and then display the user's authenticated dashboard without redirecting to the dashboard url. It looks like when I call reply.view with the request.auth.credentials after calling request.auth.session.set it is undefined. Is this because the credentials are set earlier in the pipeline and calling set doesn't update until the next request?

IE:
// do login stuff and get a user object that we want to save in session
request.auth.session.set(user);

reply.view('dashboard', { user: request.auth.credentials });

Removing expired sessions

How do we remove sessions when the browser session ends?
Or is it bad practice to use that option?

How can I set multiple session cookies with different names?

Here is my use case. I'm building new frontend app for our legacy website. Temporarily I need to provide a flow where user logs in through my new app and I set 2 cookies, one for the new app session, and one for the legacy site ( written in PHP ).

Basically I'm trying to find a way how to set new session cookie ( or a cookie with custom name and value and not protected by Iron ) so our legacy app could read it, in addition to standard session cookie provided by hapi-auth-cookie.

Maybe it's not 100% related to this plugin, but I hope you can point me to the right direction...

How to access the current "request" from within "validateFunc"?

I'm wondering whether it is possible to access the current "request" object from within the "validateFunc" callback function, for instance to check a contained IP address against the IP address of the requesting client? Is there a way I've overlooked? I would have expected that either the "request" object is passed into "validateFunc" as an additional parameter or that the "session" object has a backreference to the "request" object (perhaps directly via "session.request")...

Prepare for hapi v6.0

hapijs/hapi#1664

Just need to add attributes. For full migration to v6.0 look at the hapi6 branch (not ready for integration as hapi v6.0 has not been published, but adding attributes now is safe).

Refreshing sessions from AJAX calls

Hi guys,

I encountered a problem.
I have a web app composed of JS front + NodeJS API backend.
I use hapi + auth-cookie for sessions on the backend.
All of the frontend interaction is done with the content through AJAX API calls.
Some of these calls update data that is also present in the session.
For example it changes the user email, user being stored in the session.

I wrote code to refresh the session, but to my amazement it was not working.
After 1 day of thinking it over and over I think it has to do with the fact that all calls were AJAX and therefore the browser was not updating the session cookie.

I changed then the implementation of the hapi-auth-cookie to use a server side cache for storing the session data and in the cookie there is the sessionId.
This way my session gets refreshed correctly.

I am curious if you are interested in making this part of the plugin?

Thanks,
Daniel

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.