Is is possible to use the userId in meteor Accounts.onCreateUser? - meteor

I want to initialize the default variables for a user on creation. Is there a good way to do this - I've tried using the userId in the onCreateUser without success.
Thanks

FYI, the _id is now valid in OnCreateUser as of Meteor 0.5.8...

You could simply extend the user collection to add any properties you want:
Accounts.onCreateUser(function(options, user) {
// We still want the default hook's 'profile' behavior.
if (options.profile) {
user.profile = options.profile;
user.profile.user_status = "new";
}
return user;
});
This will not update any collection other than users, so it cannot be used to the store the new user _id as a foreign key in another collection.

Related

Meteor-Useraccounts and Accounts.onCreateUser

Am using meteor-useraccounts and alanning:roles in my Meteor webapp. The idea is that a user can register and automatically gets assigned a role. So I was thinking of using the Accounts.onCreateUser hook, however can't get that to work.
Accounts.onCreateUser(function(options, user) {
var user = user.user;
var defaultRole = ['admin'];
if (!user.roles){
Roles.addUsersToRoles(user, defaultRole);
}
});
I'm getting the following error message:
Exception while invoking method 'ATCreateUserServer' TypeError: Cannot read property 'roles' of undefined
Seems that the user is not known, hence undefined. Can you user Meteor-useraccounts and assign a role upon user creation.
NEW EDIT: tried a bit further and the below code is working but I'm not really in favor of using this as it is strange to add the role each time upon login of the user:
Accounts.onLogin(function(user) {
check(user, Object);
var user = user.user;
var defaultRole = ['admin'];
if (!user.roles){
Roles.addUsersToRoles(user, defaultRole);
}
return user;
});
There are always many ways to do that. On of which is to add the roles after the user is created and officially obtained a userId, like so:
var id = Accounts.createUser(
createOptions
);
Roles.addUsersToRoles(id, ["user","guest"]);
If you want to add roles using the hook onCreateUser you could extend the user object, like so:
Accounts.onCreateUser(function(options, user)
{
if(!options || !user) {
throw new Meteor.Error('Problem to create new user');
return;
}
var user_extend =
{
username: options.username,
email: options.email,
profile: options.profile,
roles: ["user","guest"]
};
_.extend(user,user_extend);
return user
}
I prefer method number one because you can decide when and where you want to at the roles to that user because you will set those roles to every user that registers on your site. I hope it helps.

MVC 5 Custom Application

I have implemented a custom UserStoreManager and I add same custom field into ApplicationUser.
It's work fine.
Now, I have a question. How I can get the ApplicationUser custom field value from a Controller?
I find the UserId information calling User.identity.getuserid or User.identity.getuserName but how I can access to the ApplicationUser Field?
Thank you
You just pull the user from the database. Something like:
var user = UserManager.FindById(User.Identity.GetUserId());
You need to get ApplicationUser first for the current user.
var currentUser = UserManager.FindById(HttpContext.User.Identity.GetUserId());
var customField = currentUser.CustomField;
private AppUserManager UserManager
{
get { return HttpContext.GetOwinContext().GetUserManager<AppUserManager>(); }
}

umbraco membership createuser & select profile data

I have created a class to handle membership user creation with custom fields.
I have done it based on this solutions:
How to assign Profile values?
Using ASP .NET Membership and Profile with MVC, how can I create a user and set it to HttpContext.Current.User?
namespace CCL
{
public static MemberProfile CurrentUser
{
get
{
if (Membership.GetUser() != null)
return ProfileBase.Create(Membership.GetUser().UserName) as MemberProfile;
else
return null;
}
}
}
And now I'm trying to use create the user and get the profile data:
if (Membership.GetUserNameByEmail(email) == null)
{
MembershipUser member = Membership.CreateUser(username, password, email);
Roles.AddUserToRole(username, "WebsiteUsers");
CCL.MemberProfile currentProfile = CCL.MemberProfile.CurrentUser;
bool exists = currentProfile != null;
Response.Write(exists.ToString());
}
but currentProfile is returning null.
So I'm unable to assign values from the form to my member custom properties which are handled by the properties set in the class :(
I don't get how I can make it working :(
Does anyone have some thoughts? Thanks
Suggestion 1:
Make sure that ProfileBase.Create returns something that can be cast to a "MemberProfile", otherwise if it can't then casting it will just return NULL.
Suggestion 2:
Make sure the context you are running in has a logged in user, so your call to Membership.GetUser() can find the current user object.
Other thoughts:
The ProfileBase.Create method assumes that the username you pass in is an authenticated user, I'm not sure on it's behavior when the user isn't authenticated..maybe it returns NULL?

ExtendedMembershipProvider.GetUserIDfromOauth returns what user ID?

I'm trying to customize my own implementation of ExtendedMembershipProvider. I have no idea what the GetUserIDFromOauth method is supposed to do? I see it is throwing an exception by default, and that it is supposed to return the user ID from the open auth provider.
I fail to see how this is supposed to be done, unless this means find if that user exists in the system? Is that it's purpose? I find the lack of documentation confusing...
Thanks.
GetUserIdFromOAuth is a method used by ExtendedMembershipProvider class to find User.Id in your table of users in your web application database based on Provider and ProviderUserId that you get from OAuth or OpenId Provider. After getting Provider and ProviderUserId data for a specified user, you need to save it in your database.
It returns throw new NotImplementedException(); by default. You need to implement this method to return an integer of your User.Id from your application database.
This is a sample implementation:
public override int GetUserIdFromOAuth(string provider, string providerUserId)
{
using (var context = new YourApplicationEntities())
{
// Try to find user with certain Provider and ProviderUserId
var user = context.Users.SingleOrDefault(
q => q.Provider == provider &&
q.ProviderUserId == providerUserId
);
if (user != null)
{
return user.Id;
}
}
return -1;
}
This implementation assumed that you have Provider and ProviderUserId field in your User table. If this information saved in a different table, you just need to modify the LINQ to return the desired result.

I implemented custom authentication but how to get UserID through application

I implemented custom authentication/authorization based on this tutorial http://www.mattwrock.com/post/2009/10/14/Implementing-custom-Membership-Provider-and-Role-Provider-for-Authinticating-ASPNET-MVC-Applications.aspx
It works fine. I implemented it because I don't want to have stored procedures in my database and possibility to use different RDBMS.
But I have one issue here. I authenticate user but I don't know how to store UserId somewhere so when I need to get something from database based on UserID to get it. Something like:
List<Product> products = productsRepository.GetProductsByUserId(User.UserID);
How to make this?
BTW Is there any better way to make custom authentication/authorization than this from this tutorial?
Thanks
If you've actually implemented all the methods, and you're populating the built-in MembershipUser, then simply Membership.GetUser().ProviderUserKey will return ther UserId.
in my solution I use
Docent docent = DocentRepo.GetByID(User.Identity.Name);
maybe this can be of use to you
If you're using FormsAuthentification you can encode some custom user data in your cookie / ticket besides UserName. But you have to manually create a FormsAuthenticationTicket and set UserData property to the user's id during login. This way you can have both UserName & UserId.
// during login
var authCookie = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie);
var ticket = FormsAuthentication.Decrypt(authCookie.Value);
// preserve data in your configuration
var ticketWithId = new FormsAuthenticationTicket(
version: ticket.Version,
name: ticket.Name,
issueDate: ticket.IssueDate,
expiration: ticket.Expiration,
isPersistent: ticket.IsPersistent,
userData: userId);
authCookie.Value = FormsAuthentication.Encrypt(ticketWithId);
_context.Response.Cookies.Add(authCookie);
Then you can have an extension method for Controller or HttpContext classes:
public int? GetUserId(this Controller controller) {
var identity = (FormsIdentity)controller.User.Identity;
int id;
if (int.TryParse(identity.Ticket.UserData, out id))
return id;
return null;
}
But if you don't need both UserId & UserName data for your user, than HttpContext.User.Identity.Name or Controller.User.Identity.Name will have the username for your current user

Resources