Skip to content

Commit

Permalink
working on custom claims to manage the wallet address
Browse files Browse the repository at this point in the history
  • Loading branch information
romme86 committed May 25, 2022
1 parent 24ce7ae commit 3243d28
Show file tree
Hide file tree
Showing 10 changed files with 77 additions and 46 deletions.
6 changes: 4 additions & 2 deletions vidaia/lib/models/auth0_user.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@ class Auth0User {
@JsonKey(name: 'updated_at')
final String updatedAt;

@JsonKey(name: 'https://vidaia.saynode.ch/wallet_address')
String walletAddress = '';

// userID getter to understand it easier
String get id => sub;
final String sub;

final String email;

factory Auth0User.fromJson(Map<String, dynamic> json) =>
_$Auth0UserFromJson(json);
factory Auth0User.fromJson(Map<String, dynamic> json) => _$Auth0UserFromJson(json);

Map<String, dynamic> toJson() => _$Auth0UserToJson(this);
}
4 changes: 3 additions & 1 deletion vidaia/lib/models/auth0_user.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 3 additions & 9 deletions vidaia/lib/pages/home/home/home_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,13 @@ class _HomePageState extends State<HomePage> {
children: [
Text(
'Hi, '.tr(),
style: TextStyle(
fontSize: 30,
color: PRIMARY_DARK,
fontWeight: FontWeight.w600),
style: TextStyle(fontSize: 30, color: PRIMARY_DARK, fontWeight: FontWeight.w600),
textAlign: TextAlign.center,
),
SizedBox(width: 3),
Text(
dataRepository.userinfo.displayName,
style: TextStyle(
fontSize: 30,
color: PRIMARY_DARK,
fontWeight: FontWeight.w500),
dataRepository.userinfo.name,
style: TextStyle(fontSize: 30, color: PRIMARY_DARK, fontWeight: FontWeight.w500),
textAlign: TextAlign.center,
),
],
Expand Down
4 changes: 3 additions & 1 deletion vidaia/lib/pages/home/home_page_loader.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ class _HomePage2State extends State<HomePage2> {
isDataLoaded, //Future that returns bool
]),
builder: (BuildContext context, AsyncSnapshot<List<bool>> snapshot) {
if (snapshot.connectionState == ConnectionState.done && AuthService.instance.profile != null && AuthService.instance.profile!.id.isNotEmpty && snapshot.data?[0] == true) {
bool autoLogin = snapshot.connectionState == ConnectionState.done && AuthService.instance.isLoggedIn && snapshot.data?[0] == true;
debugPrint('autologin ' + autoLogin.toString() + ' ' + (snapshot.connectionState == ConnectionState.done).toString() + ' ' + AuthService.instance.profile.id.isNotEmpty.toString() + ' ' + (snapshot.data?[0] == true).toString());
if (autoLogin) {
return HomePageStack(_pages);
} else if (snapshot.connectionState == ConnectionState.done && snapshot.hasError) {
return Padding(
Expand Down
10 changes: 9 additions & 1 deletion vidaia/lib/pages/login_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import 'package:vidaia/utils/constants.dart';
import 'package:vidaia/utils/globals.dart';
import 'package:vidaia/utils/wallet.dart';
import 'package:vidaia/services/auth_service.dart';
import 'package:vidaia/utils/globals.dart' as global;

const users = {
'a@a.com': 'password',
Expand Down Expand Up @@ -137,13 +138,20 @@ class _LoginPageState extends State<LoginPage> {
);
}

setSuccessAuthState() {
setSuccessAuthState() async {
setState(() {
isProgressing = false;
isLoggedIn = true;
name = AuthService.instance.idToken?.name;
});

if (AuthService.instance.profile.walletAddress.isEmpty) {
AuthService.instance.profile.walletAddress = await createNewWallet();
await AuthService.instance.updateUserWalletAddress(AuthService.instance.profile.walletAddress);
} else {
global.address = AuthService.instance.profile.walletAddress;
}

Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomePage2()),
Expand Down
22 changes: 12 additions & 10 deletions vidaia/lib/repositories/dataRepository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,25 @@ import 'package:vidaia/models/HistoryEntry.dart';
import 'package:vidaia/models/Reward.dart';
import 'package:vidaia/models/User.dart';
import 'package:vidaia/models/Product.dart';
import 'package:vidaia/models/auth0_user.dart';
import 'package:vidaia/services/auth_service.dart';

class DataRepository {
//can be split up in seperate repositories in the future if needd
late List<Product> _products;
late List<Reward> _rewards;
late BuyHistory _history;
late User _userinfo;
late Auth0User _userinfo;

List<Product> get products => _products;
List<Reward> get rewards => _rewards;
BuyHistory get history => _history;
User get userinfo => _userinfo;
Auth0User get userinfo => _userinfo;

Future<bool> init() async {
_products = await loadProducts();
_rewards = await loadRewards();
_userinfo = await loadUser();
_userinfo = AuthService.instance.profile;
_history = await loadHistory();
return true;
}
Expand All @@ -45,14 +47,14 @@ class DataRepository {
return list.map((e) => Reward.fromJson(e)).toList();
}

Future<User> loadUser() async {
//read json file
final jsondata = await rootBundle.rootBundle.loadString('assets/data/user.json');
//decode json data as list
final data = json.decode(jsondata) as dynamic;
// Future<User> loadUser() async {
// //read json file
// final jsondata = await rootBundle.rootBundle.loadString('assets/data/user.json');
// //decode json data as list
// final data = json.decode(jsondata) as dynamic;

return User.fromJson(data);
}
// return User.fromJson(data);
// }

Future<BuyHistory> loadHistory() async {
//read json file
Expand Down
32 changes: 28 additions & 4 deletions vidaia/lib/services/auth_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import 'package:vidaia/models/auth0_id_token.dart';
import 'package:vidaia/models/auth0_user.dart';

class AuthService {
Auth0User? profile;
Auth0User profile = Auth0User(nickname: '', name: '', email: '', picture: '', updatedAt: '', sub: '');
Auth0IdToken? idToken;
String? auth0AccessToken;
bool isLoggedIn = false;

static final AuthService instance = AuthService._internal();
factory AuthService() => instance;
Expand All @@ -22,6 +23,7 @@ class AuthService {

Future<bool> init() async {
final storedRefreshToken = await secureStorage.read(key: REFRESH_TOKEN_KEY);
debugPrint('storedRefreshToken ' + storedRefreshToken.toString());

if (storedRefreshToken == null) {
return false;
Expand All @@ -37,6 +39,8 @@ class AuthService {
),
);
final String setResult = await _setLocalVariables(result);
isLoggedIn = true;
debugPrint('isLoggedIn' + isLoggedIn.toString());
return setResult == 'Success';
} catch (e, s) {
print('error on Refresh Token: $e - stack: $s');
Expand Down Expand Up @@ -75,7 +79,7 @@ class AuthService {
AUTH0_CLIENT_ID,
AUTH0_REDIRECT_URI,
issuer: AUTH0_ISSUER,
scopes: ['openid', 'profile', 'email'], // offline_access
scopes: ['openid', 'profile', 'email', 'offline_access'],
promptValues: ['login'],

/// possible values login, none, consent, select_account
Expand Down Expand Up @@ -143,17 +147,37 @@ class AuthService {
auth0AccessToken = result.accessToken;
idToken = parseIdToken(result.idToken!);
profile = await getUserDetails(result.accessToken!);

if (result.refreshToken != null) {
await secureStorage.write(
key: REFRESH_TOKEN_KEY,
value: result.refreshToken,
);
String? refreshTokenKeyFromStorage = await secureStorage.read(key: REFRESH_TOKEN_KEY);
debugPrint('auth_service | REFRESH_TOKEN_KEY in storage is ' + refreshTokenKeyFromStorage!);
}

isLoggedIn = true;
return 'Success';
} else {
return 'Something is Wrong!';
}
}

Future<bool> updateUserWalletAddress(String walletAddress) async {
final url = Uri.https(
AUTH0_DOMAIN,
'/userinfo',
);

final responseAuth0UserInfo = await http.patch(url, headers: {
'Authorization': 'Bearer $auth0AccessToken'
}, body: {
"user_metadata": {"wallet_address": walletAddress}
}).catchError((onError) {
debugPrint(onError);
});
if (responseAuth0UserInfo.statusCode == 200) {
return true;
}
return false;
}
}
3 changes: 2 additions & 1 deletion vidaia/lib/utils/globals.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import 'dart:typed_data';

import 'package:thor_request_dart/wallet.dart';

String? address = '0x00bab3d8de4ebbefb07d53b1ff8c0f2434bd616d';
// String? address = '0x00bab3d8de4ebbefb07d53b1ff8c0f2434bd616d'; // Key for testing
String? address = '';

//TODO: Change this once server api is implemented
String? username;
Expand Down
17 changes: 7 additions & 10 deletions vidaia/lib/utils/wallet.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ createNewWallet() async {

//derive privat key from words and save it on local device
var priv = Mnemonic.derivePrivateKey(words);
global.address =
Address.publicKeyToAddressString(derivePublicKeyFromBytes(priv, false));
global.address = Address.publicKeyToAddressString(derivePublicKeyFromBytes(priv, false));

await storage.write(key: "privateKey", value: bytesToHex(priv));

return global.address;
}

//TODO: remove this for release
Expand All @@ -34,8 +35,7 @@ Future<String?> getpriv() async {
//TODO: remove this for release
setPriv() async {
final storage = FlutterSecureStorage();
final priv =
'68afea4a4d35f7555ac1d4c6b9e29199213410edfb534cb544a52301b98aa33f';
final priv = '68afea4a4d35f7555ac1d4c6b9e29199213410edfb534cb544a52301b98aa33f';
await storage.write(key: "privateKey", value: priv);
}

Expand Down Expand Up @@ -74,12 +74,10 @@ Future<Map> transferVidar(int value, String address, String url) async {

BigInt vidar = BigInt.from(value) * toVidar;

return await connect.transferToken(
wallet, address, '0x6e21867DB6572756e778883E17e7595b7f363310', vidar);
return await connect.transferToken(wallet, address, '0x6e21867DB6572756e778883E17e7595b7f363310', vidar);
}

Stream<BigInt> checkBalance() => Stream.periodic(Duration(seconds: 1))
.asyncMap((_) => _getBalance(global.address!));
Stream<BigInt> checkBalance() => Stream.periodic(Duration(seconds: 1)).asyncMap((_) => _getBalance(global.address!));

Future<BigInt> _getBalance(String address) async {
Connect connect = Connect('https://testnet.veblocks.net');
Expand Down Expand Up @@ -110,8 +108,7 @@ Future<BigInt> _getBalance(String address) async {

Map contractMeta = json.decode(jString);
Contract contract = Contract(contractMeta);
Map a = await connect.call(address, contract, 'balanceOf', [address],
'0x6e21867DB6572756e778883E17e7595b7f363310');
Map a = await connect.call(address, contract, 'balanceOf', [address], '0x6e21867DB6572756e778883E17e7595b7f363310');
var no0x = remove0x(a["data"]);
var noLeadingZeros = no0x.replaceAll("^0+", "");
var wei = BigInt.parse(noLeadingZeros, radix: 16);
Expand Down
13 changes: 6 additions & 7 deletions vidaia/lib/widgets/vidaia_drawer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,24 @@ class VidaiaDrawer extends StatelessWidget {
return Drawer(
backgroundColor: Colors.grey.shade200,
child: Padding(
padding:
const EdgeInsets.only(left: 20, right: 20, top: 50, bottom: 20),
padding: const EdgeInsets.only(left: 20, right: 20, top: 50, bottom: 20),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Row(
children: [
CircleAvatar(
backgroundColor: primaryColorBright,
foregroundImage: AssetImage("assets/images/Me.jpg"),
backgroundImage: NetworkImage(dataRepository.userinfo.picture),
radius: 35.0,
),
const SizedBox(
width: 10,
height: 100,
),
Padding(
padding: const EdgeInsets.all(8.0),
padding: const EdgeInsets.only(left: 8, right: 0, top: 8, bottom: 8),
child: Text(
dataRepository.userinfo.displayName,
dataRepository.userinfo.name,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.headline6,
),
)
Expand Down Expand Up @@ -156,8 +156,7 @@ class VidaiaDrawer extends StatelessWidget {
),
onTap: () async {
await AuthService.instance.logout();
Navigator.push(context,
MaterialPageRoute(builder: (context) => LoginPage()));
Navigator.push(context, MaterialPageRoute(builder: (context) => LoginPage()));
}),
),
]),
Expand Down

0 comments on commit 3243d28

Please sign in to comment.