Funciones para persistir (setLoggedUser) y obtener usuario logueado (getLoggedUser)

 

Aquí te dejamos el código utilizado en esta lección:

Module Accounts {
    void setLoggedUser (User user) {
        loggedUser = user

        broker.localPersistence.save("loggedUserName", user.name)
        broker.localPersistence.save("loggedUseScore", user.score)
        broker.localKeychain.save("loggedUserPassword", u.password)
    }

    User performLogin (String username, String password) {
        if (username == null || username.trim().length() < 1) {
            broker.ui.showAlert('Oops', 'Please enter your username.')
            return null
        }

        if (password == null || password.length() < 1) {
            broker.ui.showAlert('Oops', 'Please enter your password.')
            return null
        }

        Filter userNameFilter = Filter(modelName: "User")
        userNameFilter.equalTo("name", username.trim())
        Array existingUsers = broker.cloudPersistence.getWithFilter(userNameFilter)

        if (existingUsers.size() == 0) {
           broker.ui.showAlert('Oops', "There's no user with username: " + username)
           return null
        }
        User user = existingUsers.get(0)
        if (user.password != password) {
            broker.ui.showAlert('Oops', "The password you have entered is wrong.")
            return null
        }

        return user
    }

    User getLocalPersistedUser () {
        User user

        if (broker.localPersistence.hasKey("loggedUserName")) {
            user = User()
            user.name = broker.localPersistence.get("loggedUserName")
            user.score = broker.localPersistence.get("loggedUserScore")
            user.password = broker.localKeychain.get("loggedUserPassword")
        }

        return user
    }
}


RuleContext LoginContext {
    Rule login {
        Login loginExp = broker.ui.getDataSource()
        User user = Accounts.performLogin(loginExp.username, loginExp.password)

        if (user != null) {
            Accounts.setLoggedUser(user)
            Welcome welcomeDataSource = Welcome()
            welcomeDataSource.greetings = "Welcome " + user.name + " to the treasure hunt app!"
            broker.ui.push('Welcome',welcomeDataSource)
        }
    }
}

Application {
    Array treasureScores
    User loggedUser
    
    OnInit {
        treasureScores = [10, 20, 30, 50, 100]

        loggedUser = Accounts.getLocalPersistedUser()
        if (loggedUser != null) {
            Welcome welcomeDataSource = Welcome()
            welcomeDataSource.greetings = "Welcome " + loggedUser.name + " to the treasure hunt app!"
            broker.ui.push("Welcome", welcomeDataSource)
        } else {
            broker.ui.push("Login")
        }
    }
}