var auth = require('auth');
if (auth.isAuthenticated()) {
Alloy.createController("Home").getView().open();
} else {
Alloy.createController("LoginForm").getView().open();
}
The logic for "isAuthenticated()" will vary based on the individual app's requirements. In this example we are creating a library for authentication and calling the function within it. This 'auth' library will have a few functions declared as exports within that will be used in other controllers and will be outlined later in this article
<Alloy>
<Window id="loginForm" layout="vertical">
<TextField id="loginName" hintText="Username"/>
<TextField id="password" hintText="Password" passwordMask="true"/>
<Button id="loginSubmit">Login!</Button>
</Window>
</Alloy>
var args = arguments[0] || {};
$.loginSubmit.addEventListener('click', function(e) {
var auth = require('auth');
if (auth.validateCredentials($.loginName.value, $.password.value)) {
Alloy.createController("Home").getView().open();
} else {
alert("Invalid credentials!");
}
});
<Alloy>
<Window id="home" layout="vertical">
<Label>Welcome, you have been authenticated!</Label>
<Button id="logoutButton">Logout</Button>
</Window>
</Alloy>
file: /app/controllers/Home.js:
var args = arguments[0] || {};
$.logoutButton.addEventListener('click', function(e) {
var auth = require('auth');
auth.logout();
});
// Authentication library
// Custom logic to validate auth token may be required.
// In this example we are just checking to see if it exists.
exports.isAuthenticated = function() {
var authToken = Ti.App.Properties.getString("authToken");
return (authToken != undefined);
};
// Custom logic to validate the credentials will be required
// In this example we just test for a basic password
exports.validateCredentials = function(loginName, password) {
var isValid = (loginName == 'user1' && password == '1234');
if (isValid) {
// Save the auth token
Ti.App.Properties.setString("authToken", "encryptedAuthTokenString");
}
return isValid;
};
// To logout the user, remove the property and return them to the LoginForm
exports.logout = function() {
Ti.App.Properties.removeProperty("authToken");
Alloy.createController("LoginForm").getView().open();
};
<Window id="home" layout="vertical" exitOnClose="true">
<Window id="loginForm" layout="vertical" exitOnClose="true">
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)