Skip to content

Instantly share code, notes, and snippets.

@1amageek
Last active May 16, 2017 01:22
Show Gist options
  • Save 1amageek/e2ac57eb8309c3abf8869db5a9533e07 to your computer and use it in GitHub Desktop.
Save 1amageek/e2ac57eb8309c3abf8869db5a9533e07 to your computer and use it in GitHub Desktop.
Firebase Cloud Functionsを使ってFacebook AccountKitをFirebase Authと連携する ref: http://qiita.com/1amageek/items/c7adbd9f2bbf3a57d352
// AccoutKitの初期化
let accountKit: AKFAccountKit = AKFAccountKit(responseType: .authorizationCode)
// AccountKitを起動して電話番号認証を行う
func login() {
let inputStatus: String = UUID().uuidString
let viewController: AKFViewController = self.accountKit.viewControllerForPhoneLogin(with: nil, state: inputStatus) as! AKFViewController
prepareLoginViewController(viewController: viewController)
self.present(viewController as! UIViewController, animated: true, completion: nil)
}
// AccountKitの準備
func prepareLoginViewController(viewController: AKFViewController) {
viewController.delegate = self
viewController.enableSendToFacebook = true
let locale: NSLocale = NSLocale.current as NSLocale
if let countryCode: String = locale.countryCode {
viewController.defaultCountryCode = countryCode
}
}
// MARK: -
// responseを受け取ってログインする
func customLogin(_ response: AccountKitLoginResponse, block: ((FIRUser?, Error?) -> Void)?) {
FIRAuth.auth()?.signIn(withCustomToken: response.customToken) { (firUser, error) in
if let error = error {
debugPrint(error)
block?(nil, error)
return
}
block?(firUser, error)
}
}
sudo npm install -g firebase-tools
functions start
functions deploy helloWorld --trigger-http
functions logs read
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({origin: true});
const Request = require('request');
const Querystring = require('querystring');
// Config
let config = functions.config();
// Firebase account key
let serviceAccount;
let projectID = process.env.GCLOUD_PROJECT;
if (projectID == config.project.development) {
serviceAccount = require('./firebase_projects/development.json');
} else if (projectID == config.project.production) {
serviceAccount = require('./firebase_projects/production.json');
}
// Facebook AccountKit
let accountKit;
if (projectID == config.project.development) {
accountKit = require('./accountkit/development.json');
} else if (projectID == config.project.production) {
accountKit = require('./accountkit/production.json');
}
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://' + projectID + '.firebaseio.com'
});
exports.login = functions.https.onRequest((req, res) => {
// parse request
cors(req, res, () => {
let appAccessToken = ['AA', accountKit.app_id, accountKit.app_secret].join('|');
let params = {
grant_type: 'authorization_code',
code: req.body.code,
access_token: appAccessToken
};
let tokenExchangeURL = accountKit.token_exchange_base_url + '?' + Querystring.stringify(params);
// Get access token & account id
Request.get({url: tokenExchangeURL, json: true}, (error, response, body) => {
if (error) {
res.status(500).json({
errors: [{
message: 'Could not get access token.'
}]
});
return
}
let accessToken = body.access_token
let id = body.id
var meEndpointURL = accountKit.me_endpoint_base_url + '?access_token=' + accessToken;
// Get account infomation
Request.get({url: meEndpointURL, json: true }, (error, response, body) => {
if (error) {
res.status(500).json({
errors: [{
message: 'Could not get user information.'
}]
});
return
}
let countryPrefix = body.phone.country_prefix
let nationalNumber = body.phone.national_number
let number = body.phone.number
let additionalClaims = {
country_prefix: countryPrefix,
national_number: nationalNumber,
number: number
};
// Get custom token for Firebase custom login
admin.auth().createCustomToken(id, additionalClaims)
.then(function(customToken) {
// Send token back to client
res.json({
custom_token: customToken,
account_id: id,
access_token: accessToken,
country_code: countryPrefix,
national_number: nationalNumber,
phone_number: number
});
})
.catch(function(error) {
console.log("Error creating custom token:", error);
res.status(500).json({
errors: [{
message: 'Failed to get custom token.'
}]
});
});
});
});
});
})
firebase login
firebase init functions
firebase deploy
auth:import [options] [dataFile] import users into your Firebase project from a data file(.csv or .json)
auth:export [options] [dataFile] Export accounts from your Firebase project into a data file
database:get [options] <path> fetch and print JSON data at the specified path
database:push [options] <path> [infile] add a new JSON object to a list of data in your Firebase
database:set [options] <path> [infile] store JSON data at the specified path via STDIN, arg, or file
database:remove [options] <path> remove data from your Firebase at the specified path
database:update [options] <path> [infile] update some of the keys for the defined path in your Firebase
database:profile [options] profile the Realtime Database and generate a usage report
deploy [options] deploy code and assets to your Firebase project
hosting:disable [options] stop serving web traffic to your Firebase Hosting site
functions:log [options] read logs from deployed functions
functions:config:clone [options] clone environment config from another project
functions:config:get [path] fetch environment config stored at the given path
functions:config:set [values...] set environment config with key=value syntax
functions:config:unset [keys...] unset environment config at the specified path(s)
help [command] display help information
init [feature] setup a Firebase project in the current directory
list list the Firebases to which you have access
login [options] log the CLI into Firebase
login:ci [options] generate an access token for use in non-interactive environments
logout log the CLI out of Firebase
open [link] quickly open a browser to relevant project resources
serve [options] start a local server for your static assets
tools:migrate [options] ensure your firebase.json format is up to date
use [options] [alias_or_project_id] set an active Firebase project for your working directory
firebase functions:config:set my.debug=true
firebase functions:config:get
// 結果
{
"my": {
"debug": "true"
}
}
firebase functions:config:unset my
sudo npm install -g @google-cloud/functions-emulator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment