Blog

How to Logout the Current User From a Backendless App With the User Logout API

by on September 1, 2019

The Logout APIĀ is a logical counterpart for the User Login API, described in another article here. The full documentation for the Backendless REST logout API can be found here.

The logout step is not required for most apps given that the user session will expire automatically. However, some apps choose to provide the functionality, especially those with a special multiple login policy or the expectation of greater security, such as financial apps. In fact, many apps choose to include a logout function even if not necessary in order to appease privacy-minded users.

The logout API is very simple – a single line of code terminates the current session. The code for a number of the most common frontend frameworks is shown below. If there is a framework not included that you would like to see, please check our support forums.

    Asynchronous API sample (Android and Plain Java):

    final AsyncCallback<Void> logoutResponder = new AsyncCallback<Void>()
    {
        @Override
        public void handleResponse( Void aVoid )
        {
            boolean isValidLogin = Backendless.UserService.isValidLogin();
            System.out.println( "Is user logged in? - " + isValidLogin );
        }
        @Override
        public void handleFault( BackendlessFault backendlessFault )
        {
            System.out.println( "Server reported an error " + backendlessFault.getMessage() );
        }
    };
    AsyncCallback<BackendlessUser> loginResponder = new AsyncCallback<BackendlessUser>()
    {
        @Override
        public void handleResponse( BackendlessUser backendlessUser )
        {
            boolean isValidLogin = Backendless.UserService.isValidLogin();
            System.out.println( "Is user logged in? - " + isValidLogin );
            System.out.println( "Logging user out" );
            Backendless.UserService.logout( logoutResponder );
        }
        @Override
        public void handleFault( BackendlessFault backendlessFault )
        {
            System.out.println( "Server reported an error " + backendlessFault.getMessage() );
        }
    };
    System.out.println( "Logging user in" );
    Backendless.UserService.login( "spidey@backendless.com", "greeng0blin", loginResponder );

    Synchronous API sample (Plain Java only):

    System.out.println( "Logging user in" );
    BackendlessUser user = Backendless.UserService.login( "spidey@backendless.com", "greeng0blin" );
    boolean isValidLogin = Backendless.UserService.isValidLogin();
    System.out.println( "Is user logged in? - " + isValidLogin );
    System.out.println( "Logging user in" );
    Backendless.UserService.logout();
    isValidLogin = Backendless.UserService.isValidLogin();
    System.out.println( "Is user logged in? - " + isValidLogin );

    Log.i(TAG, "Logging user in")
    val user = Backendless.UserService.login("spidey@backendless.com", "greeng0blin")
    
    var isValidLogin = Backendless.UserService.isValidLogin
    Log.i(TAG, "Is user logged in? - $isValidLogin")
    
    Log.i(TAG, "Logging user out")
    Backendless.UserService.logout()
    
    isValidLogin = Backendless.UserService.isValidLogin
    Log.i(TAG, "Is user logged in? - $isValidLogin")

    NSLog(@"Logging user in");
        
    [Backendless.shared.userService loginWithIdentity:@"spidey@backendless.com" password:@"greeng0blin" responseHandler:^(BackendlessUser *user) {
          
        [Backendless.shared.userService isValidUserTokenWithResponseHandler:^(BOOL isValidLogin) {
                
            NSLog(@"Is user logged in? - %@", isValidLogin ? @"true" : @"false");
            NSLog(@"Logging user out");
                
            [Backendless.shared.userService logoutWithResponseHandler:^{
                    
                [Backendless.shared.userService isValidUserTokenWithResponseHandler:^(BOOL isValidLogin) {
                    NSLog(@"Is user logged in? - %@", isValidLogin ? @"true" : @"false");
                } errorHandler:^(Fault *fault) {
                    NSLog(@"Error: %@", fault.message);
                }];
                    
            } errorHandler:^(Fault *fault) {
                NSLog(@"Error: %@", fault.message);
            }];
                
        } errorHandler:^(Fault *fault) {
            NSLog(@"Error: %@", fault.message);
        }];
            
    } errorHandler:^(Fault *fault) {
        NSLog(@"Error: %@", fault.message);
    }];

    print("Logging user in")
            
    Backendless.shared.userService.login(identity: "spidey@backendless.com", password: "greeng0blin", responseHandler: { user in
              
        Backendless.shared.userService.isValidUserToken(responseHandler: { isValidLogin in
                    
            print("Is user logged in? - \(isValidLogin)")
            print("Logging user out")
                    
            Backendless.shared.userService.logout(responseHandler: {
                        
                Backendless.shared.userService.isValidUserToken(responseHandler: { isValidLogin in                        
                    print("Is user logged in? - \(isValidLogin)")
                }, errorHandler: { fault in
                    print("Error: \(fault.message ?? "")")
                })
                       
            }, errorHandler: { fault in
                print("Error: \(fault.message ?? "")")
            })
                   
        }, errorHandler: { fault in
            print("Error: \(fault.message ?? "")")
        })
                
    }, errorHandler: { fault in
        print("Error: \(fault.message ?? "")")
    })

    const Backendless = require('backendless')
    /*
     Or use `import Backendless from 'backendless'` for client side.
     If you don't use npm or yarn to install modules, you can add the following line
     <script src="//api.backendless.com/sdk/js/latest/backendless.min.js"></script>
     to your index.html file and use the global Backendless variable.
    */
    
    Backendless.initApp('YOUR_APP_ID', 'YOUR_JS_API_KEY')
    
    const checkIsUserLoginValid = () => {
      return Backendless.UserService.isValidLogin()
        .then(isValidLogin => console.log(`Is user logged in? - ${ isValidLogin }`))
    }
    
    const logoutUser = () => {
      console.log('Logging user out')
    
      return Backendless.UserService.logout()
    }
    
    const onError = error => {
      console.error('Server reported an error: ', error.message)
      console.error('error code: ', error.code)
      console.error('http status: ', error.status)
    }
    
    console.log('Logging user in')
    Backendless.UserService.login('spidey@backendless.com', 'greeng0blin')
      .then(checkIsUserLoginValid)
      .then(logoutUser)
      .then(checkIsUserLoginValid)
      .catch(onError)
    

    print("Logging user in");
    var user = await Backendless.UserService.login("spidey@backendless.com", "greeng0blin");
    
    bool isValidLogin = await Backendless.UserService.isValidLogin();
    print("Is user logged in? - $isValidLogin");
    
    print("Logging user out");
    await Backendless.UserService.logout();
    
    isValidLogin = await Backendless.UserService.isValidLogin();
    print("Is user logged in? - $isValidLogin");

    The code produces the following output:

    Logging user in
    Is user logged in? - true
    Logging user out
    Is user logged in? - false

    Leave a Reply