I have built a small prototype project using CloudKit JS and am now starting to build the next version of it and am wanting to use Ember as I have some basic experience with it. However, I am not too sure where to place the CloudKit JS code. For example where should I add the configure part and the auth function? I think that once I find the spot for the auth code, I could then add some of my query functions into the individual views and components, right?
Here is my configure code (with the container and id removed):
CloudKit.configure({
containers: [{
containerIdentifier: '###',
// #todo Must generate a production token for app store version
apiToken: '###',
auth: {
persist: true
},
// #todo Must switch to production for app store version
environment: 'development'
}]
});
Here is the auth function:
function setupAuth() {
// Get the container.
var container = CloudKit.getDefaultContainer();
//Function to call when user logs in
function gotoAuthenticatedState( userInfo ) {
// Checks if user allows us to look up name
var userName = '';
if ( userInfo.isDiscoverable ) {
userName = userInfo.firstName + ' ' + userInfo.lastName;
} else {
userName = 'User record name: ' + userInfo.userRecordName;
}
//Calls out initialization function
init();
//Sets up UI for logged in users
setAuthenticatedUI( userName );
//Register logged out function
container
.whenUserSignsOut()
.then( gotoUnauthenticatedState );
}
//Function to call when user logs out
function gotoUnauthenticatedState( error ) {
//Checks if error occurred
if ( error && error.ckErrorCode === 'AUTH_PERSIST_ERROR' ) {
displayError( logOutError, 'Error code: AUTH_PERSIST_ERROR' );
}
// Sets up the UI for logged out users
setUnauthenticatedUI();
//Register logged in function
container
.whenUserSignsIn()
.then( gotoAuthenticatedState )
.catch( gotoUnauthenticatedState );
}
// Check a user is signed in and render the appropriate button.
return container.setUpAuth()
.then( function( userInfo ) {
// userInfo is the signed-in user or null.
if ( userInfo ) {
gotoAuthenticatedState( userInfo );
} else {
gotoUnauthenticatedState();
}
});
}
The init() then calls functions to setup the queries to adds a chart to the page using records. The setAuthenticatedUI() and setUnauthenticatedUI() functions simply apply and remove classes once the user has been authenticated.
The answer pretty much depends on the version of Ember you're using and if how you are planning on using it. With routes? Simple routes? RouteHandlers?
For example, if you are at Ember v2.3.0, you could consider using dependency injection (https://guides.emberjs.com/v2.3.0/applications/dependency-injection/) to provide a configured container instance to the rest of your app, e.g.:
export function initialize(application) {
var container = CloudKit.configure(config).getDefaultContainer();
application.register('ckcontainer:main', container);
application.inject('route', 'ckcontainer', 'ckcontainer:main');
}
export default {
name: 'ckcontainer',
initialize: initialize
};
Then in a route, you can obtain a reference like so:
export default Ember.Route.extend({
activate() {
// The ckcontainer property is injected into all routes
var db = this.get('ckcontainer').privateCloudDatabase;
}
});
-HTH
Related
I am only able to get this to work for issues at the application level, if an error is thrown from any package in the node_modules, it is not captured.
below is my GlobalErrorHandler, i have imported this into my app.js file at the top of my application so was expecting it to capture any exception in the application.
the expected behaviour would be for the this.test() exception to be thrown and from node_modules/AnotherUIDependency and captured by the globalErrorHandler
app.js
...
import { GlobalErrorHandler } from 'MASKED/globalErrorHandler'
...
globalErrorHandler.js
import { Alert } from 'react-native'
import { GlobalStrings } from 'MASKED'
import RNExitApp from 'react-native-exit-app'
import {
setJSExceptionHandler,
setNativeExceptionHandler
} from 'react-native-exception-handler'
errorHandler = (e, isFatal) => {
Alert.alert(
GlobalStrings.globalErrorHandler.title,
// eslint-disable-next-line no-undef
errorMessage(e, isFatal, __DEV__),
[
{
text: GlobalStrings.globalErrorHandler.exit,
onPress: () => {
RNExitApp.exitApp()
}
}
],
{ cancelable: false }
)
}
errorMessage = (e, isFatal, isDev) => {
let val = null
if (isDev) {
val =
GlobalStrings.globalErrorHandler.error +
`: ${isFatal ? GlobalStrings.globalErrorHandler.fatal : ''}` +
'\n\n' +
e.name +
':' +
e.message
} else {
if (!isFatal) {
val = GlobalStrings.globalErrorHandler.exceptionMessage
} else {
val = GlobalStrings.globalErrorHandler.nonFatal + ': ' + e
}
}
return val
}
setJSExceptionHandler(errorHandler, true)
setNativeExceptionHandler(errorString => {
Alert.alert(
GlobalStrings.globalErrorHandler.nativeExceptionMessage + ': ' + errorString
)
})
node_modules/AnotherUIDependency
...
export default class myComponent extends Component {
render(
return{
this.test() // expected globalErrorHandler capture
...
}
)
}
I think it may be my usage, however, i found that i had to import my globalErrorHandler at the top of the index file of each package in my project.
I found that even if i implemented it as the docs suggest, it was not truly global as it still would not capture node_module level exceptions. I would seem that the handler only picks up exceptions where it can follow the imports to the file where the exception occurs.
In my case, we have some weird referencing going on which i think is preventiung this. I have the same issue even if i use the React-Native ErrorUtils global
You're wrong about how to get the module in.
Usage
To catch JS_Exceptions
import {setJSExceptionHandler, getJSExceptionHandler} from 'react-native-exception-handler';
.
.
// For most use cases:
// registering the error handler (maybe u can do this in the index.android.js or index.ios.js)
setJSExceptionHandler((error, isFatal) => {
// This is your custom global error handler
// You do stuff like show an error dialog
// or hit google analytics to track crashes
// or hit a custom api to inform the dev team.
});
//=================================================
// ADVANCED use case:
const exceptionhandler = (error, isFatal) => {
// your error handler function
};
setJSExceptionHandler(exceptionhandler, allowInDevMode);
// - exceptionhandler is the exception handler function
// - allowInDevMode is an optional parameter is a boolean.
// If set to true the handler to be called in place of RED screen
// in development mode also.
// getJSExceptionHandler gives the currently set JS exception handler
const currentHandler = getJSExceptionHandler();
To catch Native_Exceptions
import { setNativeExceptionHandler } from "react-native-exception-handler";
//For most use cases:
setNativeExceptionHandler(exceptionString => {
// This is your custom global error handler
// You do stuff likehit google analytics to track crashes.
// or hit a custom api to inform the dev team.
//NOTE: alert or showing any UI change via JS
//WILL NOT WORK in case of NATIVE ERRORS.
});
//====================================================
// ADVANCED use case:
const exceptionhandler = exceptionString => {
// your exception handler code here
};
setNativeExceptionHandler(
exceptionhandler,
forceAppQuit,
executeDefaultHandler
);
// - exceptionhandler is the exception handler function
// - forceAppQuit is an optional ANDROID specific parameter that defines
// if the app should be force quit on error. default value is true.
// To see usecase check the common issues section.
// - executeDefaultHandler is an optional boolean (both IOS, ANDROID)
// It executes previous exception handlers if set by some other module.
// It will come handy when you use any other crash analytics module along with this one
// Default value is set to false. Set to true if you are using other analytics modules.
I am using strapi to create APIs.
I want to implement my own Registration API and Login API.
I checked the documentation of strapi but i am not finding any custom API for this.
can any one help me on this?
Same answer, but in more detail:
Strapi creates an Auth controller automatically for you and you can overwrite its behavior.
Copy the function(s) you need (e.g. register) from this file:
node_modules/strapi-plugin-users-permissions/controllers/Auth.js
to:
your_project_root/extensions/users-permissions/controllers/Auth.js
Now you can overwrite the behavior, e.g. pass a custom field inside the registration process {"myCustomField": "hello world"} and log it to the console:
async register(ctx) {
...
...
// log the custom field
console.log(params.myCustomField)
// do something with it, e.g. check whether the value already exists
// in another content type
const itExists = await strapi.query('some-content-type').findOne({
fieldName: params.myCustomField
});
if (!itExists) {
return ctx.badRequest(...)
} else {
console.log('check success')
}
}
Actually, strapi creates an Auth controller to handle these requests. You can just change them to fit in your need.
The path to the controller is:
plugins/users-permissions/controllers/Auth.js
in order to create custom users-permissons apis on server side you have to create
src/extensions/users-permissions/strapi-server.js
and in that file can write or override existing user-permissions plugin apis
here is the example for users/me
const _ = require('lodash');
module.exports = (plugin) => {
const getController = name => {
return strapi.plugins['users-permissions'].controller(name);
};
// Create the new controller
plugin.controllers.user.me = async (ctx) => {
const user = ctx.state.user;
// User has to be logged in to update themselves
if (!user) {
return ctx.unauthorized();
}
console.log('calling about meeeeeeeeeee------')
return;
};
// Add the custom route
plugin.routes['content-api'].routes.unshift({
method: 'GET',
path: '/users/me',
handler: 'user.me',
config: {
prefix: '',
}
});
return plugin;
};
I am making a game that requires a lobby of players, but no accounts. Kind of like the game, Spyfall. I am using Meteor Sessions to know which player joined the lobby so that I can return the proper data for that specific player. I have a join.js component where the user enters in the lobby access code and the user's name. This component also redirects the user to the lobby. Join.js is at the route, /join, and the lobbies are at the route, /:lobby. Here is the join.js handleSubmit method which takes the user input and puts it in the players collection:
handleSubmit(event) {
event.preventDefault();
var party = Players.findOne({code: this.refs.code.value});
if(typeof party !== 'undefined') {
Meteor.call('players.insert', this.refs.code.value, this.refs.name.value);
var playerId = Players.findOne({"name": this.refs.name.value})._id;
Meteor.call('players.current', playerId);
location.href = "/" + this.refs.code.value;
} else {
document.getElementById("error").innerHTML = 'Please enter a valid party code';
}
I am using Sessions in the Meteor.methods in the players.js collection to get the current user.
import { Mongo } from 'meteor/mongo';
import { Session } from 'meteor/session';
Meteor.methods({
'players.insert': function(code, name) {
console.log('adding player: ', name , code);
Players.insert({code: code, name: name});
},
'players.updateAll': function(ids, characters, banners, countries, ancestors) {
for (var i = 0; i < characters.length; i++){
Players.update({_id: ids[i]}, {$set: {character: characters[i], banner: banners[i], country: countries[i], ancestor: ancestors[i]},});
}
},
'players.current': function(playerId) {
Session.set("currentPlayer", playerId);
console.log(Session.get("currentPlayer"));
},
'players.getCurrent': function() {
return Session.get("currentPlayer");
}
});
export const Players = new Mongo.Collection('players');
The console.log in the 'players.current' method returns the proper player id, but once the page redirects to /:lobby, the players.getCurrent returns undefined. I want players.getCurrent to return the same value that the console.log returns. How do I fix this issue? This is the function to get the current player id in the lobby.js:
getCurrentPlayerId() {
return Meteor.call('players.getCurrent');
}
Per the Meteor API, Meteor methods are meant to be the way you define server side behavior that you call from the client. They are really intended to be defined on the server.
Methods are remote functions that Meteor clients can invoke with Meteor.call.
A Meteor method defined on the client simply acts as a stub.
Calling methods on the client defines stub functions associated with server methods of the same name
Based on your code it looks like you are doing everything client side. In fact, session is part of the Meteor client API (can't use on the server).
Session provides a global object on the client that you can use to store an arbitrary set of key-value pairs.
Therefore, If I were you, I would just implement all this logic in some sort of util file that you can then import into the Templates where you need it. You are effectively doing the same thing, you just need to use regular functions instead of Meteor methods.
Here is an example util file (be sure to update the Players import based upon your project's file structure).
import { Players } from './players.js';
import { Session } from 'meteor/session';
export const players = {
insert: function(code, name) {
console.log('adding player: ', name , code);
return Players.insert({code: code, name: name});
},
updateAll: function(ids, characters, banners, countries, ancestors) {
for (var i = 0; i < characters.length; i++) {
Players.update({_id: ids[i]}, {$set: {character: characters[i], banner: banners[i], country: countries[i], ancestor: ancestors[i]},});
}
},
setCurrent: function(playerId) {
Session.set("currentPlayer", playerId);
console.log(Session.get("currentPlayer"));
},
getCurrent: function(unixTimestamp) {
return Session.get("currentPlayer");
},
};
Then, you can import this into whatever template you have that has defined the event handler you included in your question.
import { Template } from 'meteor/templating';
import { players } from './utils.js';
Template.template_name.events({
'click .class': handleSubmit (event, instance) {
event.preventDefault();
var party = Players.findOne({code: this.refs.code.value});
if (typeof party !== 'undefined') {
var playerId = players.insert(this.refs.code.value, this.refs.name.value);
players.setCurrent(playerId);
location.href = "/" + this.refs.code.value;
} else {
document.getElementById("error").innerHTML = 'Please enter a valid party code';
}
},
});
Of course you will need to modify the above code to use your correct template name and location of the utils file.
I think the issue is that you are using
location.href = "/" + this.refs.code.value;
instead of using
Router.go("/"+this.refs.code.value);
if using Iron Router. Doing this is as if you are refreshing the page. And here's a package to maintain Session variables across page refreshes.
I have an EmberJS application generated using ember-cli. I'm currently using simple-auth with a custom authenticator.
In the authenticator, when the user logs in I want to save his details so that I can use it later.
I have the following code:
authenticate: function(options) {
var self = this;
return new Ember.RSVP.Promise(function(resolve, reject){
API.user.login(options.username, options.password, true).done(function(data) {
// #TODO: Save current user
resolve(data.id);
}).fail(function() {
reject();
});
});
},
User data is available in the variable data.user.
I tried using Ember.set('App.currentUser', data.user); but it's not working. What should I do?
I think it works easiest to use an initializer. Theres several ways you can resolve the user, I think it is easiest if you pass the user_email alongside the grant token from the API
//initializers/session-user.js
import Ember from "ember";
import Session from "simple-auth/session";
export function initialize(container) {
Session.reopen({
setCurrentUser: function() {
var accessToken = this.get('access_token');
var self = this;
if (!Ember.isEmpty(accessToken)) {
return container.lookup('store:main').find('user', {
email: self.get('user_email')
}).then(function (users){
self.set('currentUser', users.get('firstObject'));
});
}
}.observes('access_token')
});
}
export default {
name: 'session-user',
before: 'simple-auth',
initialize: initialize
};
Check this thread for where the idea of this came from: http://discuss.emberjs.com/t/best-practice-for-loading-and-persisting-current-user-in-an-authenticated-system/6987
And if you are using simple-auth > 0.8.0-beta.1 you will need to adjust the initializer
I ended up creating a custom Sessions controller and setting the current user object there, and then creating an alias from the application controller.
Something like what's in this article.
Currently when auto publish is removed, only {{currentUser.profile.name}} works.I'm trying to get {{currentUser.profile.first_name}} and the avatar from Facebook but have not been able to do so. Here is my code...
On the Server side:
Meteor.publish('userData', function() {
if(!this.userId) return null;
return Meteor.users.find(this.userId, {fields: {
'services.facebook': 1
}});
});
On Iron Router:
Router.configure({
waitOn: function() {
return Meteor.subscribe('userData');
}
});
From my understanding, I see that Meteor is publishing all the userData and then subscribing to it via Iron Router. What I don't understand is why this is not working -- as I think {{currentUser.profile.first_name}} should work but isn't.
Like Richard suggests, when a user is created, you can copy the services document to the profile doc.
Accounts.onCreateUser(function(options, user) {
// We still want the default hook's 'profile' behavior.
if (options.profile) {
user.profile = options.profile;
user.profile.memberSince = new Date();
// Copy data from Facebook to user object
user.profile.facebookId = user.services.facebook.id;
user.profile.firstName = user.services.facebook.first_name;
user.profile.email = user.services.facebook.email;
user.profile.link = user.services.facebook.link;
}
return user;
});
Your publication to get their first name and Facebook ID would look like this...
/* ============== Single User Data =============== */
Meteor.publish('singleUser', function(id) {
check(id, String);
return Meteor.users.find(id,
{fields: {'profile.facebookId': 1, 'profile.name': 1, 'profile.firstName': 1, 'profile.link': 1}});
});
You can access a user's Facebook avatar with a template helper function...
Template.profileView.helpers({
userPicHelper: function() {
if (this.profile) {
var id = this.profile.facebookId;
var img = 'http://graph.facebook.com/' + id + '/picture?type=square&height=160&width=160';
return img;
}
}
});
In your template, you can then use the following helper (provided you are wrapping this in a block that contains user data):
<img src="{{userPicHelper}}" alt="" />
I believe you're trying to access the first_name field from the services subdocument. It should be {{currentUser.services.facebook.first_name}}
If you want to transfer first_name to the profile subdocument, you can have the following event handler:
Accounts.onCreateUser(function(options, user) {
// ... some checks here to detect Facebook login
user.profile.firstName = user.services.facebook.first_name;
user.profile.lastName = user.services.facebook.last_name;
});