Skip to content

Instantly share code, notes, and snippets.

@JesterXL
Created March 4, 2014 03:08
Show Gist options
  • Save JesterXL/9339596 to your computer and use it in GitHub Desktop.
Save JesterXL/9339596 to your computer and use it in GitHub Desktop.
Sample Dart code to login to Django
void getToken()
{
print("getToken");
getTokenService = new GetTokenService();
getTokenService.getToken().then((ServiceEvent event)
{
login();
});
}
void login()
{
print("login");
new LoginService().login(getTokenService.token,
"jessewarden", "jessewarden")
.then((ServiceEvent event)
{
onLoginSuccess(event);
})
.catchError((ServiceEvent event)
{
onLoginError(event);
});
}
part of workoutloggerlib;
class GetTokenService
{
String token;
Future getToken()
{
Completer<ServiceEvent> completer = new Completer<ServiceEvent>();
try
{
HttpRequest tokenRequest = new HttpRequest();
tokenRequest.onReadyStateChange.listen((_)
{
if (tokenRequest.readyState == HttpRequest.DONE &&
(tokenRequest.status == 200 || tokenRequest.status == 0))
{
print("getToken response: " + tokenRequest.responseText);
document.cookie = "csrfCookie=" + tokenRequest.responseText;
token = tokenRequest.responseText;
completer.complete(new ServiceEvent(ServiceEvent.GET_TOKEN_SUCCESS));
}
});
tokenRequest.onError.listen((_)
{
completer.completeError(new ServiceEvent(ServiceEvent.GET_TOKEN_ERROR));
});
tokenRequest.open("GET", ServicesLocator.GET_TOKEN);
tokenRequest.send();
}
catch(error)
{
completer.completeError(new ServiceEvent(ServiceEvent.GET_TOKEN_ERROR));
}
return completer.future;
}
}
part of workoutloggerlib;
class LoginService
{
String token;
Future login(String token, String username, String password)
{
Completer<ServiceEvent> completer = new Completer<ServiceEvent>();
try
{
// Map<String, String> json = new Map<String, String>();
// json['username'] = username;
// json['password'] = password;
String jsonData = '{"username": "jessewarden", "password": "jessewarden"}';
Map<String, String> headers = new Map<String, String>();
headers["X-CSRFToken"] = token;
headers["Content-Type"] = "text/plain";
headers["Accept"] = "text/plain";
HttpRequest.request(ServicesLocator.LOGIN,
method: "POST",
mimeType: "application/json",
requestHeaders: headers,
sendData: jsonData)
.then((HttpRequest theRequest)
{
completer.complete(new ServiceEvent(ServiceEvent.LOGIN_SUCCESS));
})
.catchError((Error error)
{
completer.completeError(new ServiceEvent(ServiceEvent.LOGIN_ERROR));
});
}
catch(error, stackTrace)
{
print(error);
print(stackTrace);
completer.completeError(new ServiceEvent(ServiceEvent.GET_TOKEN_ERROR));
}
return completer.future;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment