Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //main
- // import 'package:esport_tournamnet/ui/core.dart';
- import 'package:esport_tournamnet/ui/screen/HomePage.dart';
- import 'package:esport_tournamnet/ui/screen/Login.dart';
- import 'package:flutter/material.dart';
- import 'package:flutter_secure_storage/flutter_secure_storage.dart';
- import 'dart:convert' show json, base64, ascii;
- const SERVER_IP = 'http://10.0.2.2:1337';
- final storage = FlutterSecureStorage();
- void main() {
- runApp(MyApp());
- }
- class MyApp extends StatelessWidget {
- // This widget is the root of your application.
- Future<String> get jwtOrEmpty async {
- var jwt = await storage.read(key: "jwt");
- if (jwt == null) return "";
- return jwt;
- }
- @override
- Widget build(BuildContext context) {
- return MaterialApp(
- title: 'Flutter Demo',
- debugShowCheckedModeBanner: false,
- theme: ThemeData.dark(),
- home: FutureBuilder(
- future: jwtOrEmpty,
- builder: (context, snapshot) {
- if (!snapshot.hasData) return CircularProgressIndicator();
- if (snapshot.data != "") {
- var str = snapshot.data;
- var jwt = str.split(".");
- if (jwt.length != 3) {
- return LoginPage();
- } else {
- var payload = json.decode(ascii.decode(base64.decode(base64.normalize(jwt[1]))));
- if (DateTime.fromMillisecondsSinceEpoch(payload["exp"] * 1000).isAfter(DateTime.now())) {
- return HomePage(str, payload);
- // return HomePage();
- } else {
- return LoginPage();
- }
- }
- } else {
- return LoginPage();
- }
- }),
- );
- }
- }
- //LoginPage
- import 'package:esport_tournamnet/main.dart';
- // import 'package:esport_tournamnet/ui/core.dart';
- import 'package:esport_tournamnet/ui/screen/HomePage.dart';
- import 'package:flutter/material.dart';
- import 'package:http/http.dart' as http;
- class LoginPage extends StatelessWidget {
- final TextEditingController _emailController = TextEditingController();
- final TextEditingController _usernameController = TextEditingController();
- final TextEditingController _passwordController = TextEditingController();
- void displayDialog(context, title, text) => showDialog(
- context: context,
- builder: (context) => AlertDialog(title: Text(title), content: Text(text)),
- );
- Future<String> attemptLogIn(String email, String password) async {
- var res = await http.post(
- "$SERVER_IP/auth/local/",
- body: {"identifier": email, "password": password},
- );
- if (res.statusCode == 200) {
- print(res.headers);
- return res.body;
- }
- print(res.body);
- print("$SERVER_IP/auth/local/");
- return null;
- }
- Future<int> attemptSignUp(String email, String password, String username) async {
- var res = await http.post(
- '$SERVER_IP/users/',
- body: {"email": email, "password": password, "username": username},
- );
- return res.statusCode;
- }
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text("Log In"),
- ),
- body: Padding(
- padding: const EdgeInsets.all(8.0),
- child: Column(
- children: <Widget>[
- TextField(
- controller: _usernameController,
- decoration: InputDecoration(labelText: 'username'),
- ),
- TextField(
- controller: _emailController,
- decoration: InputDecoration(labelText: 'email'),
- ),
- TextField(
- controller: _passwordController,
- obscureText: true,
- decoration: InputDecoration(labelText: 'Password'),
- ),
- FlatButton(
- onPressed: () async {
- var email = _emailController.text;
- var password = _passwordController.text;
- var jwt = await attemptLogIn(email, password);
- if (jwt != null) {
- storage.write(key: "jwt", value: jwt);
- Navigator.push(
- context,
- // MaterialPageRoute(builder: (context) => HomePage()),
- MaterialPageRoute(builder: (context) => HomePage.fromBase64(jwt)),
- );
- } else {
- displayDialog(context, "An Error Occurred", "No account was found matching that username and password");
- }
- },
- child: Text("Log In")),
- FlatButton(
- onPressed: () async {
- var email = _emailController.text;
- var password = _passwordController.text;
- var username = _usernameController.text;
- print(_usernameController.text + ' ' + _emailController.text + ' ' + _passwordController.text);
- if (username.length < 4)
- displayDialog(context, "Invalid email", "The email should be at least 4 characters long");
- else if (password.length < 4)
- displayDialog(context, "Invalid Password", "The password should be at least 4 characters long");
- else {
- var res = await attemptSignUp(email, password, username);
- if (res == 201) {
- displayDialog(context, "Success", "The user was created. Log in now.");
- print('The user was created. Log in now.');
- } else if (res == 409)
- displayDialog(context, "That email is already registered",
- "Please try to sign up using another email or log in if you already have an account.");
- else {
- displayDialog(context, "Error", "An unknown error occurred.");
- }
- }
- },
- child: Text("Sign Up"))
- ],
- ),
- ));
- }
- }
- //HomePage
- // import 'package:esport_tournamnet/main.dart';
- import 'package:flutter/material.dart';
- import 'dart:convert' show json, base64, ascii;
- import 'package:http/http.dart' as http;
- class HomePage extends StatelessWidget {
- HomePage(this.jwt, this.payload);
- factory HomePage.fromBase64(String jwt) => HomePage(jwt, json.decode(ascii.decode(base64.decode(base64.normalize(jwt.split(".")[1])))));
- final String jwt;
- final Map<String, dynamic> payload;
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- body: Center(
- child: FutureBuilder(
- future: http.read('http://10.0.2.2:1337/auth/local/', headers: {"jwt": jwt}),
- builder: (context, shapshot) {
- return shapshot.hasData
- ? Column(
- children: <Widget>[
- // Text("${payload['username']}, here's the data:"),
- Text(shapshot.data, style: Theme.of(context).textTheme.headline4)
- ],
- )
- : shapshot.hasError
- ? Text("An error occurred")
- : CircularProgressIndicator();
- },
- ),
- ),
- );
- }
- }
Add Comment
Please, Sign In to add comment