Options
All
  • Public
  • Public/Protected
  • All
Menu

StitchAuth

StitchAuth represents and controls the login state of a StitchAppClient.

Login is required for most Stitch functionality. Decide which Authentication Provider you are using and use loginWithCredential to log in.

For OAuth2 login (e.g. Google, Facebook), you must obtain a server auth code yourself and pass it to the relevant StitchCredential. One approach is to use a third party module, e.g. install react-native-google-signin and use it to get the auth code to pass to GoogleCredential.

Once logged in, StitchAuth.user is a StitchUser object that can be examined for user profile and other information.

To log out, use logout.

Example

// Previously:
// const stitchAppClient = await Stitch.initializeDefaultAppClient('your-stitch-app-id')

// Log in with anonymous credential
stitchAppClient.auth
  .loginWithCredential(new AnonymousCredential())
  .then((user) => {
    console.log(`Logged in as anonymous user with id: ${user.id}`)
  })
  .catch(console.error)

// Log in with user/password credential
stitchAppClient.auth
  .loginWithCredential(new UserPasswordCredential('user', 'password'))
  .then((user) => {
    console.log(`Logged in as user with id: ${user.id}`)
  })
  .catch(console.error)

See Also

Hierarchy

  • StitchAuth

Index

Properties

isLoggedIn

isLoggedIn: boolean

Whether or not there is a currently logged in active user of this StitchAuth

Optional user

A StitchUser object representing the currently logged in, active user, or undefined if there is no logged in active user.

Methods

addAuthListener

  • Registers a StitchAuthListener with the client.

    Example

    // In this example, a custom StitchAuthListener is defined and registered:
    const stitchClient = Stitch.defaultAppClient
    
    // Define the listener
    const myAuthListener = {
      onUserAdded: (auth, addedUser) => {
        console.log('onUserAdded:', addedUser.profile)
      },
      onUserLoggedIn: (auth, loggedInUser) => {
        console.log('onUserLoggedIn:', loggedInUser.profile)
      },
      onActiveUserChanged: (auth, currentActiveUser, previousActiveUser) => {
        console.log('onActiveUserChanged:', currentActiveUser, previousActiveUser)
      },
      onUserLoggedOut: (auth, loggedOutUser) => {
        console.log('onUserLoggedOut:', loggedOutUser.profile)
      },
      onUserRemoved: (auth, removedUser) => {
        console.log('onUserRemoved:', removedUser.profile)
      },
      onUserLinked: (auth, linkedUser) => {
        console.log('onUserLinked:', linkedUser.profile)
      },
      onListenerRegistered: (auth) => {
        console.log('onListenerRegistered')
      },
    }
    
    // Register the listener
    const {auth} = stitchClient
    auth.addAuthListener(myAuthListener)
    
    // Console:
    //   onListenerRegistered
    
    const user = await auth.loginWithCredential(new UserPasswordCredential('user', 'password'))
    
    // Console:
    //   onUserAdded
    //   onUserLoggedIn
    //   onActiveUserChanged
    
    await auth.logout()
    
    // Console:
    //   onUserLoggedOut
    //   onActiveUserChanged
    
    await auth.removeUserWithId(user.id)
    
    // Console:
    //   onUserRemoved
    

    Parameters

    • listener: StitchAuthListener

      The listener to be triggered when an authentication event occurs on this auth object.

    Returns any

listUsers

  • Returns a list of all users who have logged into this application, except those that have been removed manually and anonymous users who have logged out.

    Note

    The list of users is a snapshot of the state when listUsers() is called. The [[StitchUsers]] in this list will not be updated if, e.g., a user's login state changes after this is called.

    Example

    const stitchAppClient = Stitch.defaultAppClient
    
    const {auth} = stitchAppClient
    
    // Log in as two different users.
    await auth.loginWithCredential(new UserPasswordCredential('user1', 'password'))
    await auth.loginWithCredential(new UserPasswordCredential('user2', 'password'))
    
    // List users.
    console.log(auth.listUsers())
    

    See Also

    Returns StitchUser[]

loginWithCredential

  • loginWithCredential(credential: StitchCredential): Promise<StitchUser>
  • Logs in as a StitchUser using the provided StitchCredential.

    Example

    // Example component that uses the react-native-google-signin module to get
    // the server auth code for Stitch to use.
    //
    // NOTE: The react-native-google-signin native module must be installed correctly
    // and your Google project must be configured.
    //
    // For more detail, see https://stackoverflow.com/questions/55145071/#55173164
    //
    // Above:
    // import {Stitch, GoogleCredential} from 'mongodb-stitch-react-native-sdk'
    // import {GoogleSignin, GoogleSigninButton} from 'react-native-google-signin'
    class GoogleLogin extends React.Component {
      // ...
    
      componentDidMount() {
        // Configure react-native-google-signin
        GoogleSignin.configure({
          webClientId: '<id>', // client ID of type WEB from Stitch
          offlineAccess: true, // allows Stitch service to use credential
          iosClientId: '<id>', // [iOS] CLIENT_ID from GoogleService-Info.plist
        })
      }
    
      _onPressLogin = async () => {
        // It's recommended to call this before signIn()
        await GoogleSignin.hasPlayServices()
    
        // Sign in via react-native-google-signin
        const userInfo = await GoogleSignin.signIn()
    
        // Retrieve the server auth code
        const {serverAuthCode} = userInfo
        if (serverAuthCode === null) {
          throw new Error('Failed to get serverAuthCode!')
        }
        try {
          // Pass auth code to Stitch with a GoogleCredential
          const {auth} = Stitch.defaultAppClient
          const user = await auth.loginWithCredential(new GoogleCredential(serverAuthCode))
    
          // Log in was successful
          console.log(`Successfully logged in as user ${user.id}`)
          this.setState({currentUserId: user.id})
        } catch (err) {
          // Login failed
          console.error(`Failed to log in: ${err}`)
          this.setState({currentUserId: undefined})
        }
      }
    
      _onPressLogout = async () => {
        // Logout react-native-google-signin
        await GoogleSignin.revokeAccess()
        await GoogleSignin.signOut()
    
        // Then log Stitch out
        const {auth} = Stitch.defaultAppClient
        const user = await auth.logout()
    
        console.log(`Successfully logged out user ${user.id}`)
        this.setState({currentUserId: undefined})
      }
    
      render() {
        let loginStatus = 'Currently logged out.'
        const {currentUserId, isSigninInProgress} = this.state
        if (currentUserId) {
          loginStatus = `Currently logged in as ${currentUserId}.`
        }
    
        // Leverage react-native-google-signin's GoogleSigninButton
        const loginButton = (
          <GoogleSigninButton
            style={{width: 192, height: 48}}
            size={GoogleSigninButton.Size.Wide}
            color={GoogleSigninButton.Color.Dark}
            onPress={this._onPressLogin}
            disabled={isSigninInProgress}
          />
        )
    
        const logoutButton = (
          <Button
            onPress={this._onPressLogout}
            title="Logout"
          />
        )
    
        return (
          <View>
            <Text> {loginStatus} </Text>
            {currentUserId === undefined ? loginButton : logoutButton}
          </View>
        )
      }
    }
    

    Parameters

    Returns Promise<StitchUser>

logout

  • logout(): Promise<void>
  • Logs out the currently authenticated active user and clears any persisted authentication information for that user.

    There will be no active user after this logout takes place, even if there are other logged in users. Another user must be explicitly switched to using switchToUserWithId or loginWithCredential.

    Example

    const stitchAppClient = Stitch.defaultAppClient
    
    const {auth} = stitchAppClient
    
    const user1 = await auth.loginWithCredential(new UserPasswordCredential('user1', 'password'))
    const user2 = await auth.loginWithCredential(new UserPasswordCredential('user2', 'password'))
    
    // Active user is now user2
    expect('Active user to be user2', auth.user.id === user2.id)
    
    await auth.logout()
    
    // The active user is now undefined. Stitch does not assume it should
    // switch to another active account upon logout
    expect('Active user to be undefined', auth.user === undefined)
    
    // Explicitly switch to a desired active user
    auth.switchToUserWithId(user1.id)
    
    expect('Active user to be user1', auth.user.id === user1.id)
    

    See Also

    Returns Promise<void>

logoutUserWithId

  • logoutUserWithId(userId: string): Promise<void>
  • Logs out the user with the provided id.

    The promise rejects with an exception if the user was not found.

    Note

    Because anonymous users are deleted after logout, this method is equivalent to removeUserWithId for anonymous users.

    Example

    const stitchAppClient = Stitch.defaultAppClient
    
    const {auth} = stitchAppClient
    
    // Log in with user/password credential. The Email/Password Provider
    // was enabled in the Stitch UI Users Panel.
    let user = await auth.loginWithCredential(new UserPasswordCredential('user', 'password'))
    
    expect('User is logged in', user.isLoggedIn)
    
    // Log out the user who just logged in.
    await auth.logoutUserWithId(user.id)
    
    // Update the user with the latest state
    user = auth.listUsers().find(entry => entry.id === user.id)
    
    expect('User is logged out', !user.isLoggedIn)
    

    Parameters

    • userId: string

      the id of the user to log out

    Returns Promise<void>

removeAuthListener

removeUser

  • removeUser(): Promise<void>
  • Logs out the active user and removes that user from the list of all users associated with this application as returned by StitchAuth.listUsers.

    Example

    const stitchAppClient = Stitch.defaultAppClient
    
    const {auth} = stitchAppClient
    
    // Log in
    const user = await auth.loginWithCredential(new UserPasswordCredential('user', 'password'))
    
    expect('Users list now contains user',
      undefined !== auth.listUsers().find(entry => entry.id === user.id))
    
    // Now remove active user
    await auth.removeUser()
    
    expect('User has been removed from list',
      undefined === auth.listUsers().find(entry => entry.id === user.id))
    

    Returns Promise<void>

removeUserWithId

  • removeUserWithId(userId: string): Promise<void>
  • Removes the user with the provided id from the list of all users associated with this application as returned by StitchAuth.listUsers.

    If the user was logged in, the user will be logged out before being removed.

    The promise rejects with an exception if the user was not found.

    Example

    const stitchAppClient = Stitch.defaultAppClient
    
    const {auth} = stitchAppClient
    
    // Log in with two users
    const user1 = await auth.loginWithCredential(new UserPasswordCredential('user1', 'password'))
    const user2 = await auth.loginWithCredential(new UserPasswordCredential('user2', 'password'))
    
    // List all logged in users
    console.log(auth.listUsers())
    
    // Now remove user1
    await auth.removeUserWithId(user1.id)
    
    // User has been removed from the list
    console.log(auth.listUsers())
    

    Parameters

    • userId: string

      the id of the user to remove

    Returns Promise<void>

switchToUserWithId

  • Switches the active user to the user with the specified id. The user must exist in the list of all users who have logged into this application, and the user must be currently logged in, otherwise this will throw a StitchClientError.

    Example

    const stitchAppClient = Stitch.defaultAppClient
    
    const {auth} = stitchAppClient
    
    // Log in as user1
    await auth.loginWithCredential(new UserPasswordCredential('user1', 'password'))
    
    // Active user is now user1
    const user1 = auth.user
    
    // Log in as user2
    await auth.loginWithCredential(new UserPasswordCredential('user2', 'password'))
    
    // Active user is now user2
    const user2 = auth.user
    
    // See that auth.user has changed upon loginWithCredential()
    expect('user1 is not user2', user1.id !== user2.id)
    
    let activeUser = auth.user
    
    // Verify that active user is user2
    expect('active user is user2', activeUser.id === user2.id)
    
    // Switch active user to to user1
    activeUser = auth.switchToUserWithId(user1.id)
    
    // Verify that active user is now user1
    expect('active user is user1', activeUser.id === user1.id)
    

    Parameters

    • userId: string

      the id of the user to switch to

    Throws

    • an exception if the user is not found, or the found user is not logged in

    Returns StitchUser

Legend

  • Module
  • Object literal
  • Variable
  • Function
  • Function with type parameter
  • Index signature
  • Type alias
  • Enumeration
  • Enumeration member
  • Property
  • Method
  • Interface
  • Interface with type parameter
  • Constructor
  • Property
  • Method
  • Index signature
  • Class
  • Class with type parameter
  • Constructor
  • Property
  • Method
  • Accessor
  • Index signature
  • Inherited constructor
  • Inherited property
  • Inherited method
  • Inherited accessor
  • Protected property
  • Protected method
  • Protected accessor
  • Private property
  • Private method
  • Private accessor
  • Static property
  • Static method

Generated using TypeDoc