Coder Social home page Coder Social logo

superlogin-client's People

Contributors

atoumbre avatar casperlamboo avatar euandreh avatar hacorbin avatar juliobetta avatar micky2be avatar peteruithoven avatar polco avatar staxmanade avatar steffende avatar sukantgujar 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

superlogin-client's Issues

possible this bug?

Noticing that the this object here is referencing the window object and not the expected instance of Superlogin.

Thinking it's because it may need this line to change from this:

            const _oauthInterval = setInterval(function () {

to this

            const _oauthInterval = setInterval(() => {

Or this line from this:

            }, 500);

to this

            }.bind(this), 500);

I noticed it when I click the "close" button on my oauth browser window.

Thoughts?

Register validation error not forwarded

It looks like register() tries to throw the data portion of an incoming error: https://github.com/micky2be/superlogin-client/blob/master/src/index.js#L297

Maybe something changed in Axios, because there isn't always a data property. Maybe this data property was moved to the response property.

The contents of an error when giving a username that already exists, as it comes into the catch inside the register method.

{
  "config": {
    "transformRequest": {},
    "transformResponse": {},
    "headers": {
      "Accept": "application/json, text/plain, */*",
      "Content-Type": "application/json;charset=utf-8"
    },
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "method": "post",
    "url": "/auth/register",
    "data": "{\"username\":\"bob\",\"email\":\"[email protected]\",\"password\":\"secret\",\"confirmPassword\":\"secret\"}"
  },
  "response": {
    "data": {
      "error": "Validation failed",
      "validationErrors": {
        "username": [
          "Username already in use"
        ]
      },
      "status": 400
    },
    "status": 400,
    "statusText": "Bad Request",
    "headers": {
      "date": "Wed, 12 Oct 2016 14:47:23 GMT",
      "etag": "W/\"66-LxtquFq4aEzEgxDmzU63QA\"",
      "connection": "keep-alive",
      "x-powered-by": "Express",
      "content-length": "102",
      "content-type": "application/json; charset=utf-8"
    },
    "config": {
      "transformRequest": {},
      "transformResponse": {},
      "headers": {
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "application/json;charset=utf-8"
      },
      "timeout": 0,
      "xsrfCookieName": "XSRF-TOKEN",
      "xsrfHeaderName": "X-XSRF-TOKEN",
      "maxContentLength": -1,
      "method": "post",
      "url": "/auth/register",
      "data": "{\"username\":\"bob\",\"email\":\"[email protected]\",\"password\":\"secret\",\"confirmPassword\":\"secret\"}"
    },
    "request": {}
  }
}

Curiously, login() checks whether data is available and otherwise throws the original error: https://github.com/micky2be/superlogin-client/blob/master/src/index.js#L276-L281

Duplicate identifier 'Promise' @types

Hello,

I'm getting this error with the latest version of superlogin-client. The build works without errors with v0.2.3.

I figured out this problem by starting the latest version of ionic where they brought back webpack. I added back in superlogin-client and then got these errors.

I'm good for now using 0.2.3. I think.

18:28:36] typescript: node_modules/@types/es6-promise/index.d.ts, line: 11
Duplicate identifier 'Promise'.

  L10:  * If you call reject your promise is rejected with the object passed to reject.
  L11:  * For consistency and debugging (eg stack traces), obj should be an instanceof Error.
  L12:  * Any errors thrown in the constructor callback will be implicitly passed to reject().

[18:28:36] typescript: node_modules/@types/es6-promise/index.d.ts, line: 42
Duplicate identifier 'Promise'.

  L42:  function resolve<T>(value?: T | Thenable<T>): Promise<T>;

[18:28:36] typescript: node_modules/typescript/lib/lib.es2015.iterable.d.ts, line: 141
Duplicate identifier 'Promise'.

 L140:      race<T>(values: Iterable<T | PromiseLike<T>>): Promise<T>;
   41:  }

[18:28:36] typescript: node_modules/typescript/lib/lib.es2015.promise.d.ts, line: 20
Duplicate identifier 'Promise'.

  L19:  * Attaches callbacks for the resolution and/or rejection of the Promise.
  L20:  * @param onfulfilled The callback to execute when the Promise is resolved.
  L21:  * @returns A Promise for the completion of which ever callback is executed.

[18:28:36] typescript: node_modules/typescript/lib/lib.es2015.promise.d.ts, line: 187
Duplicate identifier 'Promise'.

Authorization headers not send in IE11

Superlogin-client has a checkEndpoint function which checks whether the authorization headers should be send with a request to a certain endpoint. The current host for example is always included.

It looks like this check always fails on IE11 (and probably the older IE's as well).

The checkEndpoint function uses a a element to parse the url of a request. It gives the url as href and it then checks the host properly. When giving https://example.com/users as href, host should return: example.com.
I can't find this host property in Mozilla's A element documentation and on IE 11 it seems to return return nothing (not sure whether it returns undefined / null or an empty string yet). Strangly enough when I try the same in the Console of IE11 it does work, maybe there's a race condition involved.

But anyway, isn't there a better / saver way to parse a url than using a html element?

Adding a shared database

Is there a function in superlogin-client similar to to the addUserDB() function in the original superlogin module? I need to add new CouchDB databases, which can be shared by multiple users.

Why does npm superlogin-client/lib/index.js compile to es2015 module github src/index.js?

@micky2be - Based on the package.json, the npm package is configured to compile to an es2015 esModule lib, so the code is quite different from the base in this repo src/index.js.

I am not sure, but this made it more difficult for me to use with Ionic 3 and I had to stub out all the methods in a separate provider so I could more easily make the calls. Would it be easier to use the github index.js as is in general or specifically with Ionic 3 (angular 4)? I do recall that I could not use a named export in Ionic 3 import { superlogin } from 'superlogin-client';, I had to use the default export syntax import superlogin from 'superlogin-client';. Apparently, this is because there is something non-standard about the superlogin-client npm lib, at least according to Ionic. This is from the Ionic docs:

Using the named export pattern is preferred and considered best practice because it only imports/includes the portion of the library that is needed. This results in smaller, faster apps.

In some cases, importing a specific portion of a library isn’t possible. Typically, this is the case with older libraries written for the Node Environments that don’t follow the ES2015 Module standard.

Also this makes it really difficult to contribute and test if the git repo contains one version of the index.js and the npm lib is structured quite differently. I would like to contribute some changes, but need some clarification 😄 . If this is how it has to be, please provide some background on why, and some advice on the best way to configure development. Thank you!

Questions: Rationals behind superlogin-client

Hi,

thank you for this great project. I have some questions I would like to figure out, I hope you can help me.

1/ Why do we need an interceptor? Cant we just provide an Authorization Bearers to our request and let the client implement an interceptor if he wants. We could provide a way to do that without having it integrated by default.

2/ Why is superlogin-client a singleton and not a class we can instanciate multiple times?
I guess the interceptor is part of the answer...
It makes it harder to have isolated test.

3/ Would you mind accepting patch to support async storage?
(I had to implement an async storage on top of pouchdb to support node)
So I had to modify the code everywhere to support async storage.
I also added a way to provide a custom storage class to superlogin-client.

logout with expired session leaves expired sessions in data store

Calling logout (or any of the flavors) with an expired session first calls auth/refesh, which returns a 401 and deauthorizes the expired session. The logout on the server side is never completed and the session store on the server and the session key in CouchDB _users remains along with the user db Members -> user reference in the _security doc. This can be cleaned up if you call removeExpiredKeys() on the server, but while it is active, the _users session token becomes a security risk and it can cause significant clutter if you fail to implement removeExpiredKeys() on the server.

I have implemented and tested a fix that will do a normal logout (or any of the flavors) and remove all the session store from the relevant dbs. I have only tested this on CouchDB, so I do not how it plays with Cloudant? I could not see any downsides since the session is expired anyway, even if it is a hijacked session a call to logout would only mean that they could no longer use that session to access the CouchDB datastores.

Before a do a PR I could use some feedback on this, but again I do not see any downside of doing a proper logout.

http get to /user/profile does not return email field ?

this.http.get('/user/profile',{headers:headers})
.map(res => res).subscribe(data => {
console.log(data);
});

It returns the following:

{
allProviders: (2) ["facebook", "google"]
name:"harry"
providers:["local"]
sessions:25
_id:"harry"
proto:Object
}

But no email field? How can i get the email of the user?

Thanks in advance

Hot reloading issue

With the hot reloading systems of SystemJS (jspm); systemjs-hot-reloader superlogin-client's request interseptors are stacking up, per hot reload. This means the checkRefresh is called the amount of times a hot reload was performed.

This is party caused by superlogin-client returning the instance instead of the class. Which means the instance isn't recreated when the package is re-imported. Then the user code will call the configure again which will add another request interseptor to check if the session needs to be refreshed.

I'm looking into solutions that are hopefully not systemjs-hot-reloader specific or won't break in other module loading systems.

Custom Username and Password Field doesn't work

When change the parameters local.usernameField and local.passwordField in SuperLogin the super login client doesn't work.

I think that a easy way to resolve it, is to add local.usernameField and local.passwordField to the config object of superlogin-client

SuperLoginClient.refresh() and .logout()

I want to call refresh at certain points in my app so that the token is refreshed and they have in turn done the required log in for the day (just in case the app goes offline).

The problem I have is I call SuperLoginClient.login and get my session back without issue but whenever I call SuperLoginClient.refresh() I get a 401 unauthorized. This happens even if I call refresh immediately after logging in.

Edit: The same is also happening with logout() indicating it's anything that requires an authorised request.

addUserDB - Is it possible to achieve this from the client?

Hi,

My application will allow an administrator to create users and allow access to the same database. With this in mind, I need the functionality of addUserDB so the new user can be associated with the current database.

Is it possible to achieve this from the client?

TypeError: undefined is not an object (evaluating 'f.closed')

Using Sentry we get information on client side errors from our clients, this gives us info even on edge cases. This is one of them. It happened for 2 of our users in the last month, both on iOS (10.2 and 10.1.1).

Looking through our logs they attempted to use socialAuth. It happens on this line: https://github.com/micky2be/superlogin-client/blob/master/src/index.js#L499
Looks like for some reason the popup couldn't be opened and the result of window.open was undefined.
Most anoying aspect of this is that, when this happens, it will throw this error every 500ms.

Not a high priority issue, and something I hope to fix myself, but I have quite a big backlog of issues I need to fix first.

Session refresh check issue

We're running into the issue that after a while user get into a loop where superlogin-client keeps refreshing the session. We think there is something wrong with the checkRefresh() logic.
We hope the following illustration explains the issue.
The user logged in a while ago (on the issued date), he now is beyond refreshThreshold, in this case 30% of total potential session lifetime (issued till expires). (refreshThreshold: 0.3).
The session is refreshed, the issued date stays the same but the expires moves up.
After that refresh the current date is still beyond the refresh threshold, since this is calculated from the issued date until the expires date. This means that when checkRefresh is called again it will have to refresh again.

We noticed the issue because we perform a request after a successful refresh (when the refreshed event is triggered), that new request would trigger another refresh, triggering an infinite loop.

@colinskow, what do you think?

404 (Not Found) error on logout

First off, thank you for the superlogin-client plugin. And secondly, I want to apologize upfront if my question might have a very obviously answer but I am really desperate. I'm also not sure if this should rather go to the Superlogin repo or Stackoverflow...

My app and my superlogin api is hosted on Heroku (my app(angular 2) and superlogin app are separate apps) and the db is a cloudant db. I have set up the superlogin config to look like this:

 `   var config = {
    baseUrl: '/auth/',
    endpoints: ['my-superlogin-api.herokuapp.com'],
    checkExpired: 'stateChange',
    refreshThreshold: 0.5,
};

superlogin.configure(config);`

When calling the superlogin.logout(message) function, the url posts to my app url and not to the superlogin endpoint. Is this the reason why I get a 404 not found?

Typescript definitions needed

Hi.
I'm using the angular-cli ( with currently Angular 2 RC6, webpack) and want to use superlogin with it.
I created a little definition for this package and i hope it helps someone who has the same issues with the definitions as me ;)

In Angular2App/src/typings.d.ts add this:

declare var superlogin: sc.Superlogin;

declare module "superlogin-client" {
    var Superlogin: sc.Superlogin;
    export default Superlogin;
}

declare module sc {
    interface Superlogin {
        login(credentials: any): any;
        configure(config: any): void;
    }
} 

then, for example, in your user.service.ts:

import { Injectable } from '@angular/core';
import superlogin from "superlogin-client";

@Injectable()
export class UserService {

  private superloginconfig = {
    baseUrl: "http://ip:port/auth/",
    endpoints: ["ip:port"],
    noDefaultEndpoint: false,
    storage: "local",
    providers: [],
    checkExpired: "stateChange",
    refreshThreshold: 0.5
  };

  constructor() {
    superlogin.configure(this.superloginconfig);
  }

  login(): void {
    superlogin.login({
      username: "username",
      password: "password"
    }).then((response: any) => {
      console.log(response);
    }).catch((error) => {
      console.log(error);
    });
  }
}

Handle Safari's private mode

When using localStorage / sessionStorage on Safari (iOS or OS X) running in private mode the following error is thrown:

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

This happens because the quota is set to 0.
See: http://stackoverflow.com/questions/21159301/quotaexceedederror-dom-exception-22-an-attempt-was-made-to-add-something-to-st

I think we should fall back to storing the session in memory?
Maybe have an easy way to communicate to the package user that this happened?

Documentation bug: event callbacks should be without `event` argument

README specifies that event callbacks receive event object as the first argument and the second one is data:

superlogin.on('login', function(event, session) { ... });
superlogin.on('logout', function(event, message) { ... });
superlogin.on('refresh', function(event, newSession) { ... });
superlogin.on('link', function(event, provider) { ... });

Actually, data is passed as the first argument and the second one is undefined always.
It seems a copy from ng-superlogin.

Numeric error codes in addition to error messages

Yes, I know this is a superlogin issue, but at the moment, there is nobody really working that project. So I would ask here from a client perspective if it would be useful to include a codified response for errors in addition to the current message property?

Currently I am using indexOf on the message to take different action on the client on the login with an invalid username and/or password. Here are the 3 options I am handling when the login endpoint returns with error: "Unauthorized":

  1. message: "Invalid username or password"
  2. message: "Maximum failed login attempts exceeded. Your account has been locked for 10 minutes."
  3. message: "Your account is currently locked. Please wait a few minutes and try again."

If each message included a code: ##### (or errorcode: #####) with a numeric value then client logic would be not only easier, but it would not break on changes to the message text coming from superlogin. My current use case is for Invalid username or password I don't want to alert the user, just highlight the login form, for messages 2. and 3. I want to display an alert with the message contents.

It looks like superlogin only returns the error with "Unauthorized" and the message, but no other codified information, not even the status code is returned as part of the superlogin-client error response. Working with strings instead of codes makes the client code a lot more brittle. Any thoughts?

EDIT: Another case is where username or password is missing the api returns only:

error: "Username or Password missing..."

There is no message: property returned in this case, so that adds yet another case to check for, but this time looking at the error string returned. Again, a coded numeric value would make this all much easier and more immune to changes in the text messages. Also, including the status code would also help, but is not the total solution. For example, returning 401 is great so I know it means "Unauthorized", but it does not give any more detail to add more logic to the receiver.

refresh() fails with 401

I noticed recently that the refresh method makes an unauthenticated request with axios to the superlogin server and fails to return the session accordingly with a 401 error status.
I'm not quite sure if this is expected behaviour. Can someone clear this up for me? Otherwise, I'll be happy to come up with a PR to provide an authorization header in the /session request.

Sometimes getting Unauthorized on login

Sometimes when I attempt a login it first does a refresh, which results in a Unauthorized, which then rejects my login attempt.

It seems to depend on the contents of the superlogin session stored in localStorage. When the session is too old a refresh is triggered first, where login tokens are checked on the server. When these are invalid the Unauthorized error response is given. In these cases there won't be a login request triggered.

The fact that this only happens when the session is too old made it hard to reproduce for me.

I'm assuming the logins tokens become invalid after the sessionLife setting is exceeded.

Should there even be a refresh triggered when doing a login?

confirmEmail is mistaken with verifyEmail in your code.

Hi,

The route in superlogin to confirm an email is :
http://XX.XX.XXX.XXX:3002/auth/confirm-email/[TOKEN]

and in your code you try to confirm email with:
return this._http.get(`${this._config.baseUrl}/verify-email/${token}`)

Which is not good, verify-email is used to check if an email is still available or taken, here is a copy paste from the superlogin docs.

GET /confirm-email/{token}

This link is included in the confirmation email, and will mark the user as confirmed. If local.confirmEmailRedirectURL is specified in your config, it will redirect to that location with ?success=true if successful or error={error}&message={msg} if it failed. Otherwise it will generate a standard JSON response.

What value does a session refresh really add to security?

Currently, a session refresh only changes the "expired" (and "refreshed" if you have that enhancement) value of an existing token. What does this add to security?

I thought the real security comes from the frequent changing of the user token and password so that if a session was compromised it would not be available for use after it expired. If the same token and password could be refreshed indefinitely, then is it really worth refreshing it at all?

If the goal is not to expose the username and password, then a one time session with an expires 10 years in the future would do that.

Would validating the ip address on a refresh to make sure it is refreshing from the same ip be a security enhancement #72?

How about validating the ip address on refresh and an option to reissue the token and password dbURL and all by basically doing a logout (logoutAll or logoutOthers) behind the scenes and reissuing a complete new session?

I suppose the current "refresh" is really more like "extend" and I am talking more about a "renew" function. Without using the ip of the caller either way a hacker could either continually refresh a session or maybe worse, use a renew function to continually renew sessions. Yeah, is probably not a good idea. I do think that validating ip on refresh might be a good enhancement, but I still am not convinced of the value of refreshed.

The use case I could see is like what you see in a banking app, where a window pops up and says your session will be logged out due to inactivity, but you could just as easily do that with a timer that gets reset on activity and calls logout if it times out.

Error objects should be more consistent

Superlogin-client api returns very different error objects depending on what goes wrong. There are at least three different cases:

  1. No network connection: If superlogin-client can not even connect to the superlogin server there will be an error object err with a message property with value 'Network Error' and err.response and err.status will be undefined (err.response at least exists as key). I think this is due to axios.

  2. superlogin-client detects some constraint violation on the client side (for example the username field or password is missing) and rejects the api call with an error object with a single error property that has a string value explaining what is the problem, for example here:

    return Promise.reject({ error: 'Username or Password missing...' });

  3. superlogin-client successfully connects to the superlogin server, but it returns an error code (for example the credentials do not match etc.). In this case the error object is simply the response body sent by the server. Unless there is some other server side error it will have an error and a message property both of which have a string value sent by superlogin. However, the error code sent by the server gets lost here:

    function parseError(err) {

In short handling superlogin-client error handling would look something like this:

if (!err.response && err.message === 'Network Error') {
    // network connection failed
} else if (err.error && typeof err.status === 'undefined') {
  // constraint violation, err.error is a string explaining the problem
} else {
  // err is the response body sent by the server, but it might look different depending on what happened,
  // it could be the superlogin response or anything else you send on the server
  // since we do not even have the status code its hard to tell what the problem is
}

A first step to improve this would be to let attach the status code to the error object in parseError.
We could use status 0 for the case where no connection could be established.

Documentation for Angular2 wanted

It is unclear to me how I am meant to import the superlogin-client in an angular2 project. Some more documentation would be nice.

config.checkExpired?

The readme mentions:

// Sets when to check if the session is expired. 'stateChange', 'startup' or nothing.
// 'stateChange' checks every time $stateChangeStart or $routeChangeStart is fired
// 'startup' checks just on app startup. If this is blank it will never check.
  checkExpired: 'stateChange',

But when I look through the code checkExpired is only checked as boolean, and only in the configure call?

401 Unauthorized - Ionic 2 Emulate iOS

Hello,

I got this working very well with Chrome. However, when I went to deploy it to my phone and emulator I'm getting a 401 error and "uncaught promise [object object]" when I'm trying to login.

Could this have to do with the local storage settings? Ionic 2 uses its own LocalStorage.

Thanks!

Modify logout to use optional ip filtering

I am considering adding ip filtering to the logout calls, but this would first require modification of superlogin to work. The idea is that since superlogin already stores the original ip address that started a session, you could use the ip to filter out calls to logoutAll or logoutOthers in the case where a user maybe logged in on separate devices. Just thinking at this point and the ip could be used to do addition authentication as well to enhance security. The ip is already stored by superlogin on the user sessions and even though I do not see it being leveraged, I think it was added for some future possible uses. There is more related discussion I have added over at the superlogin repo issue 179, that gives more background on how this came about.

This may not be a good idea because I suppose the ip could change from the time of login to eventual logout, so it may not be worth the effort. In that case, using logoutAll and logoutOthers as they stand now assume that there is only ever one session active at any given time for one user, but the api does not have an option to prevent more than one user from logging in with the same user pass.

The biggest downside of adding the ip filtering option on logoutAll and logoutOthers is that you may end up with orphaned sessions, but the bonus would be to allow a user to login on multiple devices and still be able to have a better chance of cleaning up any orphaned sessions by using logoutAll and logoutOthers. I described some scenarios in the superlogin 179 issue, but would be interested in hearing any other take on the value of using the ip for this or any other purpose?

superlogin.authenticate() runs into an error

my code example

import PouchDB from 'pouchdb'
import CryptoPouchDB from 'crypto-pouch'
import superlogin from 'superlogin-client'

PouchDB.plugin(CryptoPouchDB)
const patientsDB = new PouchDB('patients')
patientsDB.crypto('test1234')

superlogin.authenticate().then(function () {
  console.log('LOGGED IN!!!!!!!', arguments)
})

export default {
  patientsDB
}

error message on executing superlogin.authenticate()

Uncaught (in promise) TypeError: Cannot read property 'getItem' of undefined
    at Superlogin.getSession (eval at <anonymous> (app.js:1083), <anonymous>:187:44)
    at eval (eval at <anonymous> (app.js:1083), <anonymous>:318:26)
    at Superlogin.authenticate (eval at <anonymous> (app.js:1083), <anonymous>:317:11)
    at eval (eval at <anonymous> (app.js:1529), <anonymous>:15:59)
    at Object.<anonymous> (app.js:1529)
    at __webpack_require__ (app.js:687)
    at fn (app.js:106)
    at eval (eval at <anonymous> (app.js:1543), <anonymous>:4:78)
    at Object.<anonymous> (app.js:1543)
    at __webpack_require__ (app.js:687)

config baseurl not working

I'm running superlogin with node on localhost:3000. I'm using Ionic 2 which is on localhost:8100.

I have this as my setup (I wanted to use "import superlogin from 'superlogin-client' but I was getting at type error that it couldn't be found.)

`var superlogin = require('superlogin-client').default;
superlogin.configure(config);

var config = {
// The base URL for the SuperLogin routes with leading and trailing slashes (defaults to '/auth/')
baseUrl: 'http://localhost:3000/auth/',
// A list of API endpoints to automatically add the Authorization header to
// By default the host the browser is pointed to will be added automatically
endpoints: ["localhost:3000"],
// Set this to true if you do not want the URL bar host automatically added to the list
//noDefaultEndpoint: false,
// Where to save your session token: localStorage ('local') or sessionStorage ('session'), default: 'local'
storage: 'local',
// The authentication providers that are supported by your SuperLogin host
providers: ['facebook', 'twitter'],
// Sets when to check if the session is expired. 'stateChange', 'startup' or nothing.
// 'stateChange' checks every time $stateChangeStart or $routeChangeStart is fired
// 'startup' checks just on app startup. If this is blank it will never check.
checkExpired: 'stateChange',
// A float that determines the percentage of a session duration, after which SuperLogin will automatically refresh the
// token. For example if a token was issued at 1pm and expires at 2pm, and the threshold is 0.5, the token will
// automatically refresh after 1:30pm. When authenticated, the token expiration is automatically checked on every
// request. You can do this manually by calling superlogin.checkRefresh(). Default: 0.5
refreshThreshold: 0.5
};
`

The only way I got it work was on line 68 of the index.js file was to change:

config.baseUrl = config.baseUrl || '/auth/';

to

config.baseUrl = http://localhost:3100/auth/ || '/auth/';

Before I did that I was getting an error that it could not POST to http://localhost:8100/auth/login and thats obviously because superlogin is running on 3100. I thought thats why you set the baseurl in the config object.

Any ideas? I thought may be it was the ".default" I have at the end of "var superlogin = require('superlogin-client').default;" but it won't work without the .default.

Refresh triggers refresh?

It looks like calling refresh() is handled just like any other request which triggers checkRefresh which can trigger refresh again?
checkRefresh contains a _refreshInProgress check, but this is only set to true from the checkRefresh method, which doesn't prevent a second refresh() call. Shouldn't _refreshInProgress be set from the refresh method?

Request: VerifyPassword

Is it possible to implement verify password to this api? I'd like to do offline user authentication if possible.

How to keep checking (and refreshing) session?

Is there a recommend way to keep checking (and refreshing) the session?

There is an checkExpired config option, which when enabled will validate the session after configure, but this is only once, and I'm not sure if it refreshes the session when necessary.

Error: Cannot use 'in' operator to search for 'config' in undefined

I sometimes get the following error when trying to login using the superlogin-client.

Cannot use 'in' operator to search for 'config' in undefined

It only sometimes happens, which makes this quite hard to track down. It seems to be a client side code error from the (transpiled & bundled httpInterceptor function:

{
                key: "_httpInterceptor",
                value: function() {
                    var a = this
                      , b = function(b) {
                        var c = a.getConfig()
                          , d = a.getSession();
                        return d && d.token ? a.checkRefresh().then(function() {
                            return i(b.url, c.endpoints) && (b.headers.Authorization = "Bearer " + d.token + ":" + d.password),
                            b
                        }) : Promise.resolve(b)
                    }
                      , c = function(b) {
                        var c = a.getConfig();
                        return "config"in b ? (i(b.config.url, c.endpoints) && 401 === b.status && a.authenticated() && (p.warn("Not authorized"),
                        a._onLogout("Session expired")),
                        Promise.reject(b)) : Promise.reject(b)
                    }
                    ;
                    this._http.interceptors.request.eject(this._httpRequestInterceptor),
                    this._http.interceptors.response.eject(this._httpResponseInterceptor),
                    this._httpRequestInterceptor = this._http.interceptors.request.use(b.bind(this)),
                    this._httpResponseInterceptor = this._http.interceptors.response.use(null , c.bind(this))
                }
            }

From line:

return "config"in b ? (i(b.config.url, c.endpoints) && 401 === b.status && a.authenticated() && (p.warn("Not authorized"),

I think what happens is that the http error response interceptor is sometimes called with undefined as response argument. Not sure what could cause this. It might be that we're using basicAuth on our server and it gets an invalid response when trying to do a login request.

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.