How can I make a token persistent?

Solved. I will leave the code here for anyone who needs it. This basically implements Facebook Persistance, so once you log in with facebook and close the app, you will be logged in until you click log out. I include the Log Out function too.

MainView.js

var Observable = require("FuseJS/Observable");
var Auth = require("Auth");
var isLoggedIn = Observable(false);
var storage = require("FuseJS/Storage");
var accessToken = Observable("");

accessToken.value += storage.readSync("token.txt")

if(accessToken.value !== ""){
    isLoggedIn.value = true;
}

if(isLoggedIn.value === true){
    getMe();
}

function stringContainsString(s1, s2){
    return s1.indexOf(s2) > -1;
}

var showWebView = Observable(false);

var client_id = Auth.client_id;
var url = Observable("about:blank");

function login(){

    url.value = "https://www.facebook.com/dialog/oauth?client_id=" + client_id + "&response_type=token&redirect_uri=https://www.facebook.com/connect/login_success.html";
    showWebView.value = true;
}

function logout(){
    storage.deleteSync("token.txt");
    isLoggedIn.value = false;
    console.log("presionaste el logout");
    accessToken.value = "";
}

function pageLoaded(res){
    var uri = JSON.parse(res.json).url;
    console.log("Final URI: " + uri);
    if (stringContainsString(uri, "access_token=")){
        var tmp = uri.split("access_token=")[1];
        var at = tmp.split("&")[0];
        accessToken.value = at;
        showWebView.value = false;
        isLoggedIn.value = true;
        storage.write("token.txt", accessToken.value);
        getMe();
    }
}

var myName = Observable("");
var myPicture = Observable();
var hasProfile = Observable(false);
function getMe(){
    var url = "https://graph.facebook.com/v2.5/me?fields=name&";
    url += "access_token=" + accessToken.value;

    fetch(url,{
        method:"GET"
    }).then(function(result){
        return result.json();
    }).then(function(resultJson){
        myName.value = resultJson.name;
    }).catch(function(error){
        console.log("Error: " + error);
    });


    console.log("Trying to get picture");
    var pictureUrl = "https://graph.facebook.com/v2.5/me/picture?type=large&redirect=false&access_token=" + accessToken.value;
    fetch(pictureUrl, {
        method:"GET"
    }).then(function(result){
        return result.json();
    }).then(function(resultJson){
        myPicture.value = resultJson.data.url;
        hasProfile.value = true;
    }).catch(function(error){
        console.log("Error: " + error);
    });



}


module.exports = {
    login:login,
    pageLoaded: pageLoaded,
    url: url,
    getMe : getMe,
    myName: myName,
    myPicture: myPicture,
    showWebView: showWebView,
    hasProfile: hasProfile,
    isLoggedIn: isLoggedIn,
    logout:logout
};

MainView.ux

<App Theme="Basic" ClearColor="#504f4f" ux:Class="MainView">
<DockPanel>
    <!-- IMPORT JS FILES -->
    <JavaScript File="MainView.js"/>
    <JavaScript File="Auth.js" ux:Global="Auth" />

    <!-- START: USER LOGGED IN -->
    <WhileTrue Value="{isLoggedIn}">
            <StackPanel Alignment="VerticalCenter" Margin="20,100,20,0" Clicked="{logout}">
                <Text Value="You are logged in" />
                <Button Text="Log Out" IsEnabled="True" Alignment="Default" Opacity="1"/>
            </StackPanel>
    </WhileTrue>
    <!-- END: USER LOGGED IN -->

    <!-- START: USER NOT LOGGED IN -->
    <WhileFalse Value="{isLoggedIn}">
            <StackPanel Alignment="VerticalCenter" Margin="20,100,20,0" Clicked="{login}">
                <Text Value="You are not logged in" />
                <Button Text="Log In" IsEnabled="True" Alignment="Default" Opacity="1"/>
            </StackPanel>
    </WhileFalse> 
    <!-- END: USER NOT LOGGED IN -->

            <WhileTrue Value="{showWebView}">
                    <NativeViewHost ux:Name="nvh" Background="#ddd">
                        <WebView ux:Name="webView" Url="{url}">
                            <PageLoaded>
                                <EvaluateJS Handler="{pageLoaded}">
                                    return { url : document.location.href };
                                </EvaluateJS>
                            </PageLoaded>
                        </WebView>

                        <AddingAnimation>
                            <Change nvh.Opacity="0" Duration="0.3" />
                        </AddingAnimation>
                    </NativeViewHost>
            </WhileTrue>
</DockPanel>
</App>

Auth.js

module.exports = {
    client_id : "yourappid"
};

FacebookPersistance.unoproj

{
  "RootNamespace":"",
  "Packages": [
        "Fuse.Animations",
        "Fuse.BasicTheme",
        "Fuse.Themes",
        "Fuse.Controls",
        "Fuse.Designer",
        "Fuse.Drawing",
        "Fuse.Drawing.Primitives",
        "Fuse.Effects",
        "Fuse.Elements",
        "Fuse.Entities",
        "Fuse.Gestures",
        "Fuse.Navigation",
        "Fuse.Shapes",
        "Fuse.Triggers",
        "Fuse.Reactive",
        "Fuse.Android",
        "Fuse.Desktop",
        "Fuse.iOS",
        "Fuse.UserEvents",
        "FuseCore",
        "Uno.Collections",
        "Uno.Geometry"
  ],
  "Includes": [
    "*"
  ]
}

Hi @albertolopezdev,

Really cool example you provided here!

How do you secure your pages and make sure that the user is signed in? Is it just a boolean that you use in your view?

Would be cool if you could shed some light on this :slight_smile:

Thanks in advance!

casper.aarby.sorensen@gmail.com wrote:

Hi @albertolopezdev,

Really cool example you provided here!

How do you secure your pages and make sure that the user is signed in? Is it just a boolean that you use in your view?

Would be cool if you could shed some light on this :slight_smile:

Thanks in advance!

Correct. I would make a boolean var UserLoggedIn = Observable(false); in the js file. Once the user logs in with facebook and the token is saved, UserLoggedIn.value = true; And in the .UX you would set:

<WhileFalse Value={UserLoggedIn}>
<!--Log in screen-->
</WhlieFalse> 

<WhileTrue Value={UserLoggedIn}>
<!--Main, logged in user screen-->
</WhileTrue>

If you need more help hmu in Slack! :slight_smile:

Thanks again! That seems like a good way to do this :slight_smile: (y)

Hi @albertolopezdev and thanks for the post.
I’m new in Fuse world and I try to run your code but I cannot compile project because Fuse does not find Theme, Entities, Shapes and FuseCore packages. Maybe they are not in new version of Fuse? I’m using 1.2.1.
If I delete package references in unoproj I retrieve errors on JavaScript and WebView types.

Thanks in advance