Giter Site home page Giter Site logo

phantomappdevelopment / firebase-as3 Goto Github PK

View Code? Open in Web Editor NEW
56.0 15.0 12.0 298 KB

Integrate Firebase Auth, Realtime Database and Storage in your Adobe AIR projects.

License: MIT License

AngelScript 100.00%
actionscript adobe-air firebase firebase-auth firebase-storage firebase-database firebase-rest flex

firebase-as3's Introduction

Firebase in ActionScript

Firebase is a back end platform that offers several services to aid in the development of apps and games, specially the ones that rely on server side infrastructure.

Some of its services can be accessed by using a RESTful approach. This repository contains detailed guides and examples explaining how to use those services in your Adobe AIR projects.

You won't need an ANE for these guides, all of them work only using StageWebView, URLRequest and URLLoader.

Firebase Auth

Main guide: Firebase Auth

This service allows you to securely authenticate users into your app. It uses Google Identity Toolkit to provide this service. Some of its key features are:

  • Leverages the use of OAuth, saving time and effort.
  • Authenticate with Facebook, Google, Twitter, Email, Anonymous and more.
  • Generates an authToken that can be used for secure operations against Firebase Storage and Firebase Database.

Firebase Database

Main guide: Firebase Database

This service allows you to save and retrieve text based data. Some of its key features are:

  • Securely save and retrieve data using rules and Firebase Auth.
  • Listen to changes in realtime, useful for chat based apps.
  • Data is generated in JSON, making it lightweight and fast to load.
  • Easy to model and understand data structures.
  • Filter, organize and query the data.

Firebase Storage

Main guide: Firebase Storage

This service allows you to upload and maintain all kinds of files, including images, sounds, videos and binaries. It uses Google Cloud Storage to provide this service. Some of its key features are:

  • Securely save, retrieve and delete files using rules and Firebase Auth.
  • Load end edit metadata from files.

Getting Started

This guide assumes you want to use the 3 services in the same application, you will be able to use them with a free account.

Before you start coding you need to follow these steps to prepare your application for Firebase:

  1. Create or open a project in the Firebase Console
  2. You will be presented with 3 options for adding your app to iOS, Android or Web.
  3. Click Web, a popup will appear with information about your project. Copy down your apiKey and authDomain.

From the authDomain we only need the id of the project, an example of an id is: my-app-12345.

You can read the guides in any order but it is recommended to start with the Firebase Auth guide.

FAQs

What is the difference between these guides and existing Firebase ANEs?

Firebase ANEs are based on the Android and iOS official SDKs, providing all of their native features.

These guides are based on the JavaScript SDK, which provides the same functionality from the Web browser but inside the AIR runtime.

Which are the benefits of using these guides?

These guides work on Android, iOS, Windows and OSX using only the ActionScript 3 standard library, this will greatly reduce time when reusing your implementation code for all 4 platforms.

You won't need to embed several ANEs to your project, this is very important for developers who are concerned with the app size.

They are also a great way to understand how Firebase works behind the scenes.

Free and open source!

Why only Database, Auth and Storage, what about the other Firebase features?

These guides are based on the JavaScript SDK and therefore have their same limitation of being web based only. If you need the rest of features that Firebase offers I strongly recommend using an ANE.

How did you got the documentation for Auth and Storage?

I studied the JavaScript SDK and its official documentation, then I determined the API paths, requests, results and errors.

What about Flash Player projects?

For Flash Player projects I recommend using the ExternalInterface class with the official JavaScript SDK.

Donations

Feel free to support the development of free guides and examples. Your donations are greatly appreciated.

Become a Patron!

firebase-as3's People

Contributors

agentphantom avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-as3's Issues

Google Policy Issue

Can you authenticate google account? I had tried your samples, it was okay long time ago when you released first commit. But unfortunately right now I can't do that again. It seems google has new policy for web view. When I tried to authenticate my firebase using google got this message

403 Error

"This user-agent is not permitted to make OAuth authorisation request to Google as it is classified as an embedded user-agent (also known as a web-view). Per our policy, only browsers are permitted to make authorisation requests to Google. We offer several libraries and samples for native apps to perform authorisation request in browser."

Relogging in?

I am trying to be able to login my users. I have saved my refresh token and use that in this function... but it wont work. What else do I need to login to firebase after a user closes and opens back up my application?

Here is my full login script. After it get's the refresh token it saves it to a file. Then when it needs to login again it pulls the refresh token out and sends it to handleRefreshToken

	private function handleRefreshToken(refreshToken:String):void
        {
            var header:URLRequestHeader = new URLRequestHeader("Content-Type", "application/json");
            var myObject:Object = new Object();
            myObject.grant_type = "refresh_token";
            myObject.refresh_token = refreshToken;	
            var request:URLRequest = new URLRequest("https://securetoken.googleapis.com/v1/token?key="+FIREBASE_API_KEY);
            request.method = URLRequestMethod.POST;
            request.data = JSON.stringify(myObject);
            request.requestHeaders.push(header);
            var loader:URLLoader = new URLLoader();
            loader.addEventListener(Event.COMPLETE, refreshTokenLoaded);
            loader.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
            loader.load(request);
        }
		
		private function refreshTokenLoaded(e:Event):void 
		{
			e.target.removeEventListener(Event.COMPLETE, refreshTokenLoaded);
			var rawData:Object = JSON.parse(e.currentTarget.data);
			
			if (rawData.access_token == null)
			{
				toggleContent(0);
				toggleIntro();
				Dialog.service.toast("There was a problem logging you in. Please try again.");
				FirebaseCrash.service.report(new Error("Login Error", 0));
			}
			else
			{
				authToken = rawData.access_token;
				trace("REFRESH TOKEN LOADED.");
				trace(e.target.data);
				
				trace("Init tutorial");
				
				if (signingIn)
				{
					toggleContent(CONTENT_FRAME);
					toggleHomeScreen();
				}
				else
				{
					//Init bio fill//
					toggleProfile(true);
				}
			}

Firebase Phone Auth

Thanks you for your good job!

Do you know Firebase Phone Auth

if yes, Do you plan to add it?

Facebook login after Google login fails.

Hello @reyco1 and @sfxworks

I was researching about the issue of using the same email address for Facebook and Google login, it seems it doesn't work for security reasons.

You can see in this thread an explanation about it.

I will quote the relevant part for future readers:

To minimize the login UI clicks without compromising the account security, Firebase Authentication has a concept of 'trusted provider', where the identity provider is also the email service provider. For example, Google is the trusted provider for @gmail.com addresses, Yahoo is the trusted provider for @yahoo.com addresses, and Microsoft for @outlook.com addresses.

In the "One Account per Email address" mode, Firebase Authentication tries to link account based on email address. If a user logins from trusted provider, the user immediately signs into the account since we know the user owns the email address.

If there is an existing account with the same email address but created with non-trusted credentials (e.g. non-trusted provider or password), the previous credentials are removed for security reason. A phisher (who is not the email address owner) might create the initial account - removing the initial credential would prevent the phisher from accessing the account afterwards.

I will also update the examples later today to add a popup explaining the error.

Messaging?

My previous plan for messaging was to set up some sort of private node in the database and have both clients connect to it in real-time. Although, I'm noticing some truncated text at times...

So! Is cloud messaging possible? What's the difference? How does it work?

Typo in "Email and Password" section

Hi,

It's been a while :)

Actually, I'm not sure if it's a typo, or if they've changed things over at Firebase. Anyway, the correct request type to verify an email address is "VERIFY_EMAIL" and not "EMAIL_VERIFY". The latter returns a status 400 error.

HTH. Cheers!

error request uploading file with progress

hello,

Thanks for your tutorial.Very usefull.
i can upload file (without progress event) but
i have a error ("bad request") when i want to upload file.with progress event.

Please where is my fault?
public static function uploadFileVideo(authToken:String,url,file:File):void
{ var header:URLRequestHeader = new URLRequestHeader("Authorization", "Bearer " + authToken);
var request:URLRequest = new URLRequest(Constants.FIREBASE_STORAGE_URL +url)
request.requestHeaders.push(header);
file.addEventListener(ProgressEvent.PROGRESS, progressHandler);
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadCompleteDataHandler);

        var fileStream:FileStream = new FileStream();
        fileStream.open(file, FileMode.READ);

        var bytes:ByteArray = new ByteArray();
        fileStream.readBytes(bytes);
        fileStream.close();

       // var request:URLRequest = new URLRequest(url)
        request.method = URLRequestMethod.POST;
        request.data = bytes.toString();
        request.contentType = "application/octet-stream";

        file.uploadUnencoded(request);

	}

upload files using File.upload?

I would like a progress bar for my uploader. I hear the only way to get progress events to fire is through file.upload. How would I do this?

Images uploaded to Firebase Storage don't load in Flex

So I followed your guide uploading images to storage and works perfectly. However, images uploaded to a folder (/images/) are not loaded in Image component in flex.

If the images is uploaded to root, works perfectly so my guess is that something is wrong with the %2F .

ex.
.appspot.com/leo.jpg <- this loads
.appspot.com/images%2Fleo.jpg <- this doesnt

Any ideas?
Thanks.

Sort

Do all of these methods work?
https://firebase.google.com/docs/database/rest/retrieve-data

I am trying to order my data alphabetically. After I turn my data into an Object I can't turn it into an array and sort it.

var sorted:Array = e.data //JSON.parse result
sorted.sortOn("1");

I saw that REST isn't able to keep list items at order either. I want to sort all the items I get from a JSON node alphanumerically.

Delete à folder

Hello!
How to delete à folder (and sublime folders)?
Thanks.

Is it possible to implement onDisconnect method?

In Javascript, it is possible to pre-define the function/codes to be executed on the server side through the onDisconnect event. (such as remove its content)

Is it possible to do so in AS3?

Thanks in advance.

Image Upload in FlashPlayer

Hi,

I am new to GitHub. So I don't think this should go here. But I found this works for uploading an image using flashplayer as opposed to AIR (i.e. no 'fileReference.uploadUnencoded()'). Useful if you are doing a web based app and don't wanna use java etc. Might wanna add this to the Upload example code section.

var appID:String = "YOUR-APP-ID";

public function uploadFile(): void {
			var fileRef: FileReference = new FileReference();
			var fileFilter: FileFilter = new FileFilter("Images", "*.jpg");
			fileRef.addEventListener(Event.SELECT, fileSelected)
			fileRef.browse([fileFilter]);
			function fileSelected(event: Event): void {
				fileRef.addEventListener(Event.COMPLETE, onFileLoaded);
				fileRef.addEventListener(IOErrorEvent.IO_ERROR, ioError);
				fileRef.addEventListener(ProgressEvent.PROGRESS, onProgress);
				fileRef.load();
			}
			function onFileLoaded(event: Event): void {
				var fr: FileReference = event.target as FileReference;
				var data: ByteArray = fr["data"];
				fileRef.removeEventListener(Event.COMPLETE, onFileLoaded);
				fileRef.removeEventListener(IOErrorEvent.IO_ERROR, ioError);
				fileRef.removeEventListener(ProgressEvent.PROGRESS, onProgress);

				var request: URLRequest = new URLRequest("https://firebasestorage.googleapis.com/v0/b/"+appID+".appspot.com/o/ArtWorks%2F" + fr.name);
				request.method = URLRequestMethod.POST;
				request.data = data;

				var loader: URLLoader = new URLLoader();
				loader.addEventListener(flash.events.Event.COMPLETE, uploadComplete);
				loader.addEventListener(flash.events.IOErrorEvent.IO_ERROR, ioError);
				loader.load(request);
			}
			
			function uploadComplete(event:Event):void{
				trace("upload complete")
			}

			function ioError(event: IOErrorEvent): void {
				trace("ioError")
			}
			function onProgress(event: ProgressEvent): void {
				trace(event.bytesLoaded + "/" + event.bytesTotal);
			}
		}

Getting Google And Facebook tokens

This is sort of related. I am trying to get google and facebook auth tokens to use so I can pass to a java firebase ane. I have been trying to pass the auth-tokens I get from signing in but they aren't working. Is this because I'm getting firebase's auth tokens and not the providers? If so..can you explain to me how I can get these?

A couple of requests

Great work on this 👍

Although it's for AS3, you were right when you said that it's easy to adapt to other languages :)

I was wondering if you could provide the processes to sign a user out of firebase, and link accounts as described on this article?

Thanks!

NSURLErrorDomain error -999

Is anyone else getting this issue on the FederatedExample.mxml example while implementing it on AIR on iOS?

Error #2044: Unhandled ErrorEvent:. text=The operation couldn’t be completed. (NSURLErrorDomain error -999.)

These are my AppTransportSecurity nodes in my iOS Info Additions in the app description xml file:

key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>firebaseio.com</key> <dict> <key>NSExceptionAllowsInsecureHTTPLoads</key> <true/> <key>NSIncludesSubdomains</key> <true/> <key>NSExceptionRequiresForwardSecrecy</key> <true/> </dict> <key>googleapis.com</key> <dict> <key>NSExceptionAllowsInsecureHTTPLoads</key> <true/> <key>NSIncludesSubdomains</key> <true/> <key>NSExceptionRequiresForwardSecrecy</key> <true/> </dict> <key>firebaseapp.com</key> <dict> <key>NSExceptionAllowsInsecureHTTPLoads</key> <true/> <key>NSIncludesSubdomains</key> <true/> <key>NSExceptionRequiresForwardSecrecy</key> <true/> </dict> <key>facebook.com</key> <dict> <key>NSExceptionAllowsInsecureHTTPLoads</key> <true/> <key>NSIncludesSubdomains</key> <true/> <key>NSExceptionRequiresForwardSecrecy</key> <true/> </dict> </dict> </dict>

not Working on Device(AIR)

HI,
The code works fine in the Air simulator, but don't work on device, I think is related to the URLStream.

I'm using myflashlabs anes for device, and your examples for debugging.

Thanks for the examples

~Sebas

Questions about URLStream

First, I would like to thank you for setting up the documentation.

This may not be an issue, but there are something I am not sure about the URLStream for the Realtime Database.

Based on my testing in web using javascript, whenever there is a change in the database inside a node, it returns everything that the node contains, instead of 'only the changes'.

I would like to know, if URLStream is possible to kind of 'return everything contained by the node' in the ProgressEvent?

requestType strings have changed

snippet from: https://firebase.google.com/docs/auth/custom-email-handler

switch (mode) {
case 'resetPassword':
// Display reset password handler and UI.
handleResetPassword(auth, actionCode);
break;
case 'recoverEmail':
// Display email recovery handler and UI.
handleRecoverEmail(auth, actionCode);
break;
case 'verifyEmail':
// Display email verification handler and UI.
handleVerifyEmail(auth, actionCode);
break;
default:
// Error: invalid mode.
}

OSX Mojave can not login Error 400

Can You help me? On OSX Mojave I can not login but on Hight Sierra evrything is working perfectly. I am developing an Air Desktop app.
Animate added to privacy enabled but on Mojave login always return 400 error code.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.