Created
April 13, 2018 05:43
-
-
Save vemarav/73ad632097d022adf8e0e8980bbe9d66 to your computer and use it in GitHub Desktop.
Flutter Authentication Flow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:flutter/material.dart'; | |
import 'package:shared_preferences/shared_preferences.dart'; | |
import 'package:http/http.dart' as http; | |
import 'auth_utils.dart'; | |
class NetworkUtils { | |
static final String host = productionHost; | |
static final String productionHost = 'https://authflow.herokuapp.com'; | |
static final String developmentHost = 'http://192.168.31.110:3000'; | |
static dynamic authenticateUser(String email, String password) async { | |
var uri = host + AuthUtils.endPoint; | |
try { | |
final response = await http.post( | |
uri, | |
body: { | |
'email': email, | |
'password': password | |
} | |
); | |
final responseJson = json.decode(response.body); | |
return responseJson; | |
} catch (exception) { | |
print(exception); | |
if(exception.toString().contains('SocketException')) { | |
return 'NetworkError'; | |
} else { | |
return null; | |
} | |
} | |
} | |
static logoutUser(BuildContext context, SharedPreferences prefs) { | |
prefs.setString(AuthUtils.authTokenKey, null); | |
prefs.setInt(AuthUtils.userIdKey, null); | |
prefs.setString(AuthUtils.nameKey, null); | |
Navigator.of(context).pushReplacementNamed('/'); | |
} | |
static showSnackBar(GlobalKey<ScaffoldState> scaffoldKey, String message) { | |
scaffoldKey.currentState.showSnackBar( | |
new SnackBar( | |
content: new Text(message ?? 'You are offline'), | |
) | |
); | |
} | |
static fetch(var authToken, var endPoint) async { | |
var uri = host + endPoint; | |
try { | |
final response = await http.get( | |
uri, | |
headers: { | |
'Authorization': authToken | |
}, | |
); | |
final responseJson = json.decode(response.body); | |
return responseJson; | |
} catch (exception) { | |
print(exception); | |
if(exception.toString().contains('SocketException')) { | |
return 'NetworkError'; | |
} else { | |
return null; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment