Skip to content
This repository was archived by the owner on Mar 17, 2025. It is now read-only.

Commit bc2ff09

Browse files
author
amablue
committed
Added Firebase Auth cocos sample app.
PiperOrigin-RevId: 148408685
1 parent 3db2b31 commit bc2ff09

File tree

10 files changed

+453
-0
lines changed

10 files changed

+453
-0
lines changed

analytics/Classes/FirebaseAnalyticsScene.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535

3636
USING_NS_CC;
3737

38+
3839
/// Padding for the UI elements.
3940
static const float kUIElementPadding = 10.0;
4041

analytics/Classes/FirebaseAnalyticsScene.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
#include "FirebaseCocos.h"
2828
#include "FirebaseScene.h"
2929

30+
3031
class FirebaseAnalyticsScene : public FirebaseScene {
3132
public:
3233
static cocos2d::Scene *createScene();

auth/Classes/FirebaseAuthScene.cpp

Lines changed: 270 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,270 @@
1+
// Copyright 2017 Google Inc. All rights reserved.
2+
//
3+
// Permission is hereby granted, free of charge, to any person obtaining a copy
4+
// of this software and associated documentation files (the "Software"), to
5+
// deal in the Software without restriction, including without limitation the
6+
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7+
// sell copies of the Software, and to permit persons to whom the Software is
8+
// furnished to do so, subject to the following conditions:
9+
//
10+
// The above copyright notice and this permission notice shall be included in
11+
// all copies or substantial portions of the Software.
12+
//
13+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16+
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19+
// SOFTWARE.
20+
21+
#include "FirebaseAuthScene.h"
22+
23+
#include <stdarg.h>
24+
25+
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
26+
#include <android/log.h>
27+
#include <jni.h>
28+
#include "platform/android/jni/JniHelper.h"
29+
#endif
30+
31+
#include "FirebaseCocos.h"
32+
#include "firebase/auth.h"
33+
34+
USING_NS_CC;
35+
36+
/// Padding for the UI elements.
37+
static const float kUIElementPadding = 10.0;
38+
39+
/// Placeholder labels for the text fields.
40+
static const char* kEmailPlaceholderText = "Email";
41+
static const char* kPasswordPlaceholderText = "Password";
42+
43+
/// Creates the Firebase scene.
44+
Scene* CreateFirebaseScene() {
45+
return FirebaseAuthScene::createScene();
46+
}
47+
48+
/// Creates the FirebaseAuthScene.
49+
Scene* FirebaseAuthScene::createScene() {
50+
// Create the scene.
51+
auto scene = Scene::create();
52+
53+
// Create the layer.
54+
auto layer = FirebaseAuthScene::create();
55+
56+
// Add the layer to the scene.
57+
scene->addChild(layer);
58+
59+
return scene;
60+
}
61+
62+
/// Initializes the FirebaseScene.
63+
bool FirebaseAuthScene::init() {
64+
using firebase::auth::Auth;
65+
using firebase::auth::Credential;
66+
using firebase::auth::EmailAuthProvider;
67+
68+
if (!Layer::init()) {
69+
return false;
70+
}
71+
72+
auto visibleSize = Director::getInstance()->getVisibleSize();
73+
cocos2d::Vec2 origin = Director::getInstance()->getVisibleOrigin();
74+
75+
CCLOG("Initializing the Auth with Firebase API.");
76+
Auth* auth = Auth::GetAuth(firebase::App::GetInstance());
77+
78+
// Create the Firebase label.
79+
auto firebaseLabel =
80+
Label::createWithTTF("Firebase-Auth", "fonts/Marker Felt.ttf", 20);
81+
nextYPosition =
82+
origin.y + visibleSize.height - firebaseLabel->getContentSize().height;
83+
firebaseLabel->setPosition(
84+
cocos2d::Vec2(origin.x + visibleSize.width / 2, nextYPosition));
85+
this->addChild(firebaseLabel, 1);
86+
87+
const float scrollViewYPosition = nextYPosition -
88+
firebaseLabel->getContentSize().height -
89+
kUIElementPadding * 2;
90+
// Create the ScrollView on the Cocos2d thread.
91+
cocos2d::Director::getInstance()
92+
->getScheduler()
93+
->performFunctionInCocosThread(
94+
[=]() { this->createScrollView(scrollViewYPosition); });
95+
96+
logMessage("Created the Auth %x class for the Firebase app.",
97+
static_cast<int>(reinterpret_cast<intptr_t>(auth)));
98+
99+
// It's possible for CurrentUser() to be non-null if the previous run
100+
// left us in a signed-in state.
101+
if (auth->CurrentUser() == nullptr) {
102+
logMessage("No user signed in at creation time.");
103+
} else {
104+
logMessage("Current user %s already signed in, so signing them out.",
105+
auth->CurrentUser()->DisplayName().c_str());
106+
}
107+
108+
email_text_field_ = createTextField(kEmailPlaceholderText);
109+
this->addChild(email_text_field_);
110+
111+
password_text_field_ = createTextField(kPasswordPlaceholderText);
112+
password_text_field_->setPasswordEnabled(true);
113+
this->addChild(password_text_field_);
114+
115+
register_user_button_ = createButton(true, "Register user");
116+
register_user_button_->addTouchEventListener(
117+
[this, auth](Ref* sender, cocos2d::ui::Widget::TouchEventType type) {
118+
cocos2d::ui::Button* button = static_cast(sender);
119+
switch (type) {
120+
case cocos2d::ui::Widget::TouchEventType::ENDED: {
121+
this->logMessage("Registering user...");
122+
const char* email = email_text_field_->getString().c_str();
123+
const char* password = password_text_field_->getString().c_str();
124+
this->create_user_future_ =
125+
auth->CreateUserWithEmailAndPassword(email, password);
126+
this->register_user_button_->setEnabled(false);
127+
break;
128+
}
129+
default: {
130+
break;
131+
}
132+
}
133+
});
134+
this->addChild(register_user_button_);
135+
136+
credentialed_sign_in_button_ = createButton(true, "Sign in");
137+
credentialed_sign_in_button_->addTouchEventListener(
138+
[this, auth](Ref* sender, cocos2d::ui::Widget::TouchEventType type) {
139+
cocos2d::ui::Button* button = static_cast(sender);
140+
switch (type) {
141+
case cocos2d::ui::Widget::TouchEventType::ENDED: {
142+
this->logMessage("Signing in...");
143+
const char* email = email_text_field_->getString().c_str();
144+
const char* password = password_text_field_->getString().c_str();
145+
Credential email_cred =
146+
EmailAuthProvider::GetCredential(email, password);
147+
this->sign_in_future_ = auth->SignInWithCredential(email_cred);
148+
this->credentialed_sign_in_button_->setEnabled(false);
149+
this->anonymous_sign_in_button_->setEnabled(false);
150+
this->sign_out_button_->setEnabled(true);
151+
this->anonymous_sign_in_ = false;
152+
break;
153+
}
154+
default: {
155+
break;
156+
}
157+
}
158+
});
159+
this->addChild(credentialed_sign_in_button_);
160+
161+
anonymous_sign_in_button_ = createButton(true, "Sign in anonymously");
162+
anonymous_sign_in_button_->addTouchEventListener(
163+
[this, auth](Ref* sender, cocos2d::ui::Widget::TouchEventType type) {
164+
cocos2d::ui::Button* button = static_cast(sender);
165+
switch (type) {
166+
case cocos2d::ui::Widget::TouchEventType::ENDED: {
167+
this->logMessage("Signing in anonymously...");
168+
// Anonymous sign in must be enabled in the Firebase Console.
169+
this->sign_in_future_ = auth->SignInAnonymously();
170+
this->credentialed_sign_in_button_->setEnabled(false);
171+
this->anonymous_sign_in_button_->setEnabled(false);
172+
this->sign_out_button_->setEnabled(true);
173+
this->anonymous_sign_in_ = true;
174+
break;
175+
}
176+
default: {
177+
break;
178+
}
179+
}
180+
});
181+
this->addChild(anonymous_sign_in_button_);
182+
183+
sign_out_button_ = createButton(false, "Sign out");
184+
sign_out_button_->addTouchEventListener(
185+
[this, auth](Ref* sender, cocos2d::ui::Widget::TouchEventType type) {
186+
cocos2d::ui::Button* button = static_cast(sender);
187+
switch (type) {
188+
case cocos2d::ui::Widget::TouchEventType::ENDED: {
189+
this->logMessage("Signed out");
190+
auth->SignOut();
191+
this->credentialed_sign_in_button_->setEnabled(true);
192+
this->anonymous_sign_in_button_->setEnabled(true);
193+
this->sign_out_button_->setEnabled(false);
194+
break;
195+
}
196+
default: {
197+
break;
198+
}
199+
}
200+
});
201+
this->addChild(sign_out_button_);
202+
203+
// Create the close app menu item.
204+
auto closeAppItem = MenuItemImage::create(
205+
"CloseNormal.png", "CloseSelected.png",
206+
CC_CALLBACK_1(FirebaseScene::menuCloseAppCallback, this));
207+
closeAppItem->setContentSize(cocos2d::Size(25, 25));
208+
// Position the close app menu item on the top-right corner of the screen.
209+
closeAppItem->setPosition(cocos2d::Vec2(
210+
origin.x + visibleSize.width - closeAppItem->getContentSize().width / 2,
211+
origin.y + visibleSize.height -
212+
closeAppItem->getContentSize().height / 2));
213+
214+
// Create the Menu for touch handling.
215+
auto menu = Menu::create(closeAppItem, NULL);
216+
menu->setPosition(cocos2d::Vec2::ZERO);
217+
this->addChild(menu, 1);
218+
219+
// Schedule the update method for this scene.
220+
this->scheduleUpdate();
221+
222+
return true;
223+
}
224+
225+
// Called automatically every frame. The update is scheduled in `init()`.
226+
void FirebaseAuthScene::update(float /*delta*/) {
227+
using firebase::auth::AuthError;
228+
if (create_user_future_.status() == firebase::kFutureStatusComplete) {
229+
const AuthError error = static_cast(create_user_future_.error());
230+
if (error == firebase::auth::kAuthErrorNone) {
231+
logMessage("Created new user successfully.");
232+
} else {
233+
logMessage("ERROR: User creation failed: %d, `%s`", error,
234+
sign_in_future_.error_message());
235+
}
236+
this->register_user_button_->setEnabled(true);
237+
create_user_future_.Release();
238+
}
239+
if (sign_in_future_.status() == firebase::kFutureStatusComplete) {
240+
const AuthError error = static_cast(sign_in_future_.error());
241+
if (error == firebase::auth::kAuthErrorNone) {
242+
logMessage("Signed in successfully.");
243+
} else {
244+
logMessage("ERROR: Sign in failed: %d, `%s`", error,
245+
sign_in_future_.error_message());
246+
if (this->anonymous_sign_in_) {
247+
logMessage("You may need to enable anonymous login in the Firebase "
248+
"Console.");
249+
logMessage("(In the console, navigate to Authentication > "
250+
"Sign-in Method > Anonymous and click Enable)");
251+
}
252+
this->credentialed_sign_in_button_->setEnabled(true);
253+
this->anonymous_sign_in_button_->setEnabled(true);
254+
this->sign_out_button_->setEnabled(false);
255+
}
256+
sign_in_future_.Release();
257+
}
258+
}
259+
260+
/// Handles the user tapping on the close app menu item.
261+
void FirebaseAuthScene::menuCloseAppCallback(Ref* pSender) {
262+
CCLOG("Cleaning up Auth C++ resources.");
263+
264+
// Close the cocos2d-x game scene and quit the application.
265+
Director::getInstance()->end();
266+
267+
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
268+
exit(0);
269+
#endif
270+
}

auth/Classes/FirebaseAuthScene.h

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// Copyright 2017 Google Inc. All rights reserved.
2+
//
3+
// Permission is hereby granted, free of charge, to any person obtaining a copy
4+
// of this software and associated documentation files (the "Software"), to
5+
// deal in the Software without restriction, including without limitation the
6+
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7+
// sell copies of the Software, and to permit persons to whom the Software is
8+
// furnished to do so, subject to the following conditions:
9+
//
10+
// The above copyright notice and this permission notice shall be included in
11+
// all copies or substantial portions of the Software.
12+
//
13+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16+
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19+
// SOFTWARE.
20+
21+
#ifndef FIREBASE_COCOS_CLASSES_FIREBASE_AUTH_SCENE_H_
22+
#define FIREBASE_COCOS_CLASSES_FIREBASE_AUTH_SCENE_H_
23+
24+
#include "cocos2d.h"
25+
#include "ui/CocosGUI.h"
26+
27+
#include "FirebaseCocos.h"
28+
#include "FirebaseScene.h"
29+
#include "firebase/auth.h"
30+
#include "firebase/future.h"
31+
32+
class FirebaseAuthScene : public FirebaseScene {
33+
public:
34+
static cocos2d::Scene *createScene();
35+
36+
bool init() override;
37+
38+
void update(float delta) override;
39+
40+
void menuCloseAppCallback(cocos2d::Ref *pSender) override;
41+
42+
CREATE_FUNC(FirebaseAuthScene);
43+
private:
44+
/// A text field where a login email address may be entered.
45+
cocos2d::ui::TextField* email_text_field_;
46+
47+
/// A text field where a login password may be entered.
48+
cocos2d::ui::TextField* password_text_field_;
49+
50+
/// A button that uses the given email and password to register a user.
51+
cocos2d::ui::Button* register_user_button_;
52+
53+
/// A button that uses the given email and password to log in.
54+
cocos2d::ui::Button* credentialed_sign_in_button_;
55+
56+
/// A button that logs in anonymously.
57+
cocos2d::ui::Button* anonymous_sign_in_button_;
58+
59+
/// A button that logs the user out regardless of how they logged in.
60+
cocos2d::ui::Button* sign_out_button_;
61+
62+
/// A future that completes some time after attempting to create a new user.
63+
firebase::Future create_user_future_;
64+
65+
/// A future that completes some time after one of the login buttons is
66+
/// pressed.
67+
firebase::Future sign_in_future_;
68+
69+
/// Keeps track of whether or not the sign in attempt was made anonymously.
70+
bool anonymous_sign_in_;
71+
};
72+
73+
#endif // FIREBASE_COCOS_CLASSES_FIREBASE_AUTH_SCENE_H_

auth/Podfile

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
source 'https://github.com/CocoaPods/Specs.git'
2+
3+
platform :ios, '7.0'
4+
5+
target 'HelloCpp-mobile' do
6+
pod 'Firebase/Core'
7+
pod 'Firebase/Auth'
8+
end

0 commit comments

Comments
 (0)