public static bool GetUserInfo(User user, UserStorageContext storage) { // set up the FB API context FBGraphAPI fbApi = new FBGraphAPI(); UserCredential cred = user.GetCredential(UserCredential.FacebookConsent); if (cred != null && cred.AccessToken != null) { fbApi.AccessToken = cred.AccessToken; } else { TraceLog.TraceError(TRACE_NO_FB_TOKEN); return false; } // store user information from Facebook in UserProfile UserProfile userProfile = storage.ClientFolder.GetUserProfile(user); if (userProfile == null) { TraceLog.TraceError("Could not access UserProfile to import Facebook information into."); return false; } try { // import information about the current user // using foreach because the Query API returns an IEnumerable, but there is only one result foreach (var userInfo in fbApi.Query("me", FBQueries.BasicInformation)) { // import FacebookID userProfile.FacebookID = (string)userInfo[FBQueryResult.ID]; // import name if not already set if (userProfile.FirstName == null) userProfile.FirstName = (string)userInfo["first_name"]; if (userProfile.LastName == null) userProfile.LastName = (string)userInfo["last_name"]; // import picture if not already set if (userProfile.Picture == null) userProfile.Picture = String.Format("https://graph.facebook.com/{0}/picture", userProfile.FacebookID); // import birthday if not already set if (userProfile.Birthday == null) userProfile.Birthday = (string)userInfo[FBQueryResult.Birthday]; // import gender if not already set if (userProfile.Gender == null) userProfile.Gender = (string)userInfo[FBQueryResult.Gender]; // import geolocation if not already set if (userProfile.GeoLocation == null) userProfile.GeoLocation = (string)((FBQueryResult)userInfo[FBQueryResult.Location])[FBQueryResult.Name]; TraceLog.TraceInfo("Imported Facebook information into UserProfile"); } } catch (Exception ex) { TraceLog.TraceException("Facebook query for basic User information failed", ex); return false; } return true; }
// Factory method to create a new item processor based on the item type public static ItemProcessor Create(User user, UserStorageContext storage, Guid itemTypeID) { if (itemTypeID == SystemItemTypes.Task) return new TaskProcessor(user, storage); if (itemTypeID == SystemItemTypes.Appointment) return new AppointmentProcessor(user, storage); if (itemTypeID == SystemItemTypes.Grocery) return new GroceryProcessor(user, storage); if (itemTypeID == SystemItemTypes.Contact) return new ContactProcessor(user, storage); return null; }
public GoogleClient(User user, UserStorageContext storage) { // for using existing access token with renewal this.user = user; this.storage = storage; if (user.UserCredentials == null || user.UserCredentials.Count == 0) { // ensure UserCredentials are present this.user = storage.GetUser(user.ID, true); } UserCredential googleConsent = this.user.GetCredential(UserCredential.GoogleConsent); if (googleConsent != null) { this.googleAuthenticator = CreateGoogleAuthenticator(GetAccessToken); } }
public static bool DeleteItemReferences(User currentUser, UserStorageContext storageContext, Item item) { string itemID = item.ID.ToString(); var itemRefs = storageContext.Items.Include("FieldValues"). Where(i => i.UserID == currentUser.ID && i.ItemTypeID == SystemItemTypes.Reference && i.FieldValues.Any(fv => fv.FieldName == FieldNames.EntityRef && fv.Value == itemID)).ToList(); bool commit = false; foreach (var itemRef in itemRefs) { storageContext.Items.Remove(itemRef); commit = true; } // commit deletion of References if (commit) { storageContext.SaveChanges(); } return commit; }
// get or create the UserProfile item in the $Client folder for given user public UserProfile GetUserProfile(User user) { Folder clientFolder = Get(user); if (clientFolder != null) { Item item = storage.GetOrCreateItem(user, clientFolder, SystemEntities.UserProfile); Item metaItem = storage.UserFolder.GetEntityRef(user, item); if (item != null && metaItem != null) { return new UserProfile(item, metaItem); } } return null; }
// get or create a List by value in given folder for given user public Item GetOrCreateListByValue(User user, Folder folder, string value, string name, Guid? itemTypeID = null) { if (itemTypeID == null) { itemTypeID = SystemItemTypes.NameValue; } try { // get the list with given value in given folder if (Items.Any(i => i.UserID == user.ID && i.FolderID == folder.ID && i.FieldValues.Any(fv => fv.FieldName == FieldNames.Value && fv.Value == value))) { return Items.Single(i => i.UserID == user.ID && i.FolderID == folder.ID && i.FieldValues.Any(fv => fv.FieldName == FieldNames.Value && fv.Value == value)); } else { // create new list with given value and name in given folder DateTime now = DateTime.UtcNow; var list = new Item() { ID = Guid.NewGuid(), Name = name, FolderID = folder.ID, UserID = user.ID, IsList = true, ItemTypeID = itemTypeID.Value, ParentID = null, Created = now, LastModified = now, FieldValues = new List<FieldValue>() }; list.GetFieldValue(FieldNames.Value, true).Value = value; Items.Add(list); SaveChanges(); TraceLog.TraceInfo(string.Format("Created list by value '{0}' in folder '{1}' for user '{2}'", value, folder.Name, user.Name)); return list; } } catch (Exception ex) { TraceLog.TraceException(string.Format("Could not find or create list by value '{0}' in folder '{1}' for user '{2}'", value, folder.Name, user.Name), ex); return null; } }
// get or create the CalendarSettings item in the $Client folder for given user public CalendarSettings GetCalendarSettings(User user) { Folder clientFolder = Get(user); if (clientFolder != null) { Item item = storage.GetOrCreateItem(user, clientFolder, SystemEntities.CalendarSettings); Item metaItem = storage.UserFolder.GetEntityRef(user, item); if (item != null && metaItem != null) { return new CalendarSettings(item, metaItem); } } return null; }
public static HttpCookie CreateAuthCookie(User user) { bool renewFBToken; return CreateAuthCookie(user, out renewFBToken); }
// get or create a List by name in given folder for given user public Item GetOrCreateList(User user, Folder folder, string name, Guid? itemTypeID = null) { return GetOrCreateItem(user, folder, name, itemTypeID, true); }
// get or create an reference to the given entity in the UserFolder EntityRefs list public Item GetEntityRef(User user, ServerEntity entity) { Item entityRefsList = GetEntityRefsList(user); if (entityRefsList == null) return null; var entityID = entity.ID.ToString(); try { // get existing reference to given entity if (storage.Items.Include("FieldValues").Any(i => i.UserID == user.ID && i.FolderID == entityRefsList.FolderID && i.ParentID == entityRefsList.ID && i.FieldValues.Any(fv => fv.FieldName == FieldNames.EntityRef && fv.Value == entityID))) { return storage.Items.Include("FieldValues").Single(i => i.UserID == user.ID && i.FolderID == entityRefsList.FolderID && i.ParentID == entityRefsList.ID && i.FieldValues.Any(fv => fv.FieldName == FieldNames.EntityRef && fv.Value == entityID)); } else { // create new reference to given entity DateTime now = DateTime.UtcNow; var entityRefItemID = Guid.NewGuid(); var entityRefItem = new Item() { ID = entityRefItemID, Name = entity.Name, FolderID = entityRefsList.FolderID, UserID = user.ID, ItemTypeID = SystemItemTypes.Reference, ParentID = entityRefsList.ID, Created = now, LastModified = now, FieldValues = new List<FieldValue>() { new FieldValue() { ItemID = entityRefItemID, FieldName = FieldNames.EntityRef, Value = entityID }, new FieldValue() { ItemID = entityRefItemID, FieldName = FieldNames.EntityType, Value = entity.GetType().Name }, } }; storage.Items.Add(entityRefItem); storage.SaveChanges(); TraceLog.TraceInfo(String.Format("Created entity ref item {0} for user {1}", entity.Name, user.Name)); return entityRefItem; } } catch (Exception ex) { TraceLog.TraceException(String.Format("Created entity ref item {0} for user {1}", entity.Name, user.Name), ex); return null; } }
// get or create a list for an ItemType in the UserFolder for given user public Item GetListForItemType(User user, Guid itemTypeID) { Folder userFolder = Get(user); if (userFolder != null) { return storage.GetOrCreateListByValue(user, userFolder, itemTypeID.ToString(), SystemItemTypes.Names[itemTypeID]); } return null; }
public AppointmentProcessor(User user, UserStorageContext storage) { this.user = user; this.storage = storage; }
// add an operation to the Operations table public Operation CreateOperation(User user, string opType, int? code, object body, object oldBody, string session = null) { Operation operation = null; try { // add the operation to the Operations table string name; Type bodyType = body.GetType(); Guid id = (Guid)bodyType.GetProperty("ID").GetValue(body, null); if (body is Suggestion) { // Suggestion does not have a Name property, use GroupDisplayName property name = (string)bodyType.GetProperty("GroupDisplayName").GetValue(body, null); } else { name = (string)bodyType.GetProperty("Name").GetValue(body, null); } operation = new Operation() { ID = Guid.NewGuid(), UserID = user.ID, Username = user.Name, EntityID = id, EntityName = name, EntityType = bodyType.Name, OperationType = opType, StatusCode = (int?)code, Body = JsonSerializer.Serialize(body), OldBody = JsonSerializer.Serialize(oldBody), Session = session, Timestamp = DateTime.Now }; Operations.Add(operation); if (SaveChanges() < 1) { // log failure to record operation TraceLog.TraceError("Failed to record operation: " + opType); } } catch (Exception ex) { // log failure to record operation TraceLog.TraceException("Failed to record operation", ex); } return operation; }
static MembershipUser AsMembershipUser(User user) { MembershipUser member = null; if (user != null) { member = new MembershipUser( typeof(UserMembershipProvider).Name, // provider user.Name, // username user.ID, // user key user.Email, // email null, // password question null, // comment true, // isApproved false, // isLockedOut user.CreateDate, // createDate DateTime.Now, // lastLoginDate DateTime.Now, // lastActivityDate DateTime.Now, // lastPasswordChangeDate DateTime.Now); // lastLockoutDate } return member; }
public UserDataModel(UserStorageContext storage, User user) { this.storageContext = storage; this.currentUser = user; }
public UserDataModel(BaseResource resource) { this.storageContext = resource.StorageContext; this.currentUser = resource.CurrentUser; }
public UserDataModel(BaseController controller) { this.storageContext = controller.StorageContext; this.currentUser = controller.CurrentUser; }
private void SetAuthCookie(string username, bool persistent) { if (Membership.Provider is UserMembershipProvider) { User user = new User { Name = username }; HttpCookie authCookie = UserMembershipProvider.CreateAuthCookie(user, out this.renewFBToken); this.Response.Cookies.Add(authCookie); } else { FormsAuthentication.SetAuthCookie(username, persistent); } }
// get or create the $WebClient folder for given user public Folder GetWeb(User user) { return storage.GetOrCreateFolder(user, SystemEntities.WebClient, SystemItemTypes.NameValue); }
public TaskProcessor(User user, UserStorageContext storage) { this.user = user; this.storage = storage; }
// get or create the UserFolder for given user public Folder Get(User user) { return storage.GetOrCreateFolder(user, SystemEntities.User, SystemItemTypes.System); }
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { status = MembershipCreateStatus.Success; UserStorageContext storage = Storage.NewUserContext; const string emailPattern = "^[a-z0-9_\\+-]+([\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$"; if (!Regex.IsMatch(email.ToLower(), emailPattern)) { // not valid email address status = MembershipCreateStatus.InvalidEmail; TraceLog.TraceInfo("Failed to create user account due to invalid email: " + email); return null; } if (password.Length < MinRequiredPasswordLength) { // not a valid password status = MembershipCreateStatus.InvalidPassword; TraceLog.TraceInfo("Failed to create user account due to invalid password: "******"Failed to create duplicate user account: " + username); return null; } // create salt for each user and store hash of password string salt = CreateSalt(64); password = HashPassword(password, salt); Guid userID = (providerUserKey != null && providerUserKey is Guid) ? (Guid)providerUserKey : Guid.NewGuid(); User user = new User() { ID = userID, Name = username.ToLower(), Email = email.ToLower(), CreateDate = DateTime.UtcNow }; UserCredential credentials = new UserCredential() { UserID = user.ID, CredentialType = UserCredential.Password, AccessToken = password, RenewalToken = salt, LastModified = user.CreateDate }; user.UserCredentials = new List<UserCredential>() { credentials }; storage.Users.Add(user); storage.SaveChanges(); user = storage.Users.Single<User>(u => u.Name == username); status = MembershipCreateStatus.Success; // Log creation of new user account TraceLog.TraceInfo("Created new user account: " + username); return AsMembershipUser(user); }
// get or create the EntityRefs list in the UserFolder for given user public Item GetEntityRefsList(User user) { Folder userFolder = Get(user); if (userFolder != null) { return storage.GetOrCreateList(user, userFolder, SystemEntities.EntityRefs); } return null; }
// get or create an Item by name in given folder for given user (include FieldValues if NOT a List) public Item GetOrCreateItem(User user, Folder folder, string name, Guid? itemTypeID = null, bool isList = false) { if (itemTypeID == null) { itemTypeID = SystemItemTypes.NameValue; } try { // get the list with given name in given folder if (Items.Any(i => i.UserID == user.ID && i.FolderID == folder.ID && i.Name == name)) { if (isList) return Items.Single(i => i.UserID == user.ID && i.FolderID == folder.ID && i.Name == name); else return Items.Include("FieldValues").Single(i => i.UserID == user.ID && i.FolderID == folder.ID && i.Name == name); } else { // create new item with given name in given folder DateTime now = DateTime.UtcNow; var item = new Item() { ID = Guid.NewGuid(), Name = name, FolderID = folder.ID, UserID = user.ID, IsList = isList, ItemTypeID = itemTypeID.Value, ParentID = null, Created = now, LastModified = now }; Items.Add(item); SaveChanges(); TraceLog.TraceInfo(string.Format("Created item named '{0}' in folder '{1}' for user '{2}'", name, folder.Name, user.Name)); return item; } } catch (Exception ex) { TraceLog.TraceException(string.Format("Could not find or create item named '{0}' in folder '{1}' for user '{2}'", name, folder.Name, user.Name), ex); return null; } }
// get Item by ID (including FieldValues) public Item GetItem(User user, Guid itemID) { if (Items.Any(i => i.UserID == user.ID && i.ID == itemID)) { return Items.Include("FieldValues").Single<Item>(i => i.UserID == user.ID && i.ID == itemID); } return null; }
public static bool ImportFriendsAsPossibleContacts(User user, UserStorageContext userContext) { // set up the FB API context FBGraphAPI fbApi = new FBGraphAPI(); UserCredential cred = user.GetCredential(UserCredential.FacebookConsent); if (cred != null && cred.AccessToken != null) { fbApi.AccessToken = cred.AccessToken; } else { TraceLog.TraceError(TRACE_NO_FB_TOKEN); return false; } // get or create the list for Contact item types in the UserFolder Item possibleContactsList = userContext.UserFolder.GetListForItemType(user, SystemItemTypes.Contact); if (possibleContactsList == null) { TraceLog.TraceError("Could not retrieve or create the possible contacts list"); return false; } // get the current list of all possible contacts for this user var currentPossibleContacts = userContext.Items.Include("FieldValues").Where(ps => ps.UserID == user.ID && ps.FolderID == possibleContactsList.FolderID && ps.ParentID == possibleContactsList.ID && ps.ItemTypeID == SystemItemTypes.NameValue && ps.FieldValues.Any(fv => fv.FieldName == FieldNames.FacebookID)).ToList(); // get the current list of all Items that are Contacts for this user var currentContacts = userContext.Items.Include("FieldValues"). Where(c => c.UserID == user.ID && c.ItemTypeID == SystemItemTypes.Contact).ToList(); // get all the user's friends and add them as serialized contacts to the possible contacts list DateTime now = DateTime.UtcNow; try { var results = fbApi.Query("me", FBQueries.Friends).ToList(); TraceLog.TraceInfo(String.Format("Found {0} Facebook friends", results.Count)); foreach (var friend in results) { // check if a possible contact by this name and with this FBID already exists - and if so, skip it if (currentPossibleContacts.Any( ps => ps.Name == (string)friend[FBQueryResult.Name] && ps.FieldValues.Any(fv => fv.FieldName == FieldNames.FacebookID && fv.Value == (string)friend[FBQueryResult.ID]))) continue; bool process = true; // check if a contact by this name already exists var existingContacts = currentContacts.Where(c => c.Name == (string)friend[FBQueryResult.Name]).ToList(); foreach (var existingContact in existingContacts) { var fbFV = existingContact.GetFieldValue(FieldNames.FacebookID, true); if (fbFV.Value == null) { // contact with this name exists but no FacebookID, assume same and set the FacebookID fbFV.Value = (string)friend[FBQueryResult.ID]; var sourcesFV = existingContact.GetFieldValue(FieldNames.Sources, true); sourcesFV.Value = string.IsNullOrEmpty(sourcesFV.Value) ? Sources.Facebook : string.Concat(sourcesFV.Value, ",", Sources.Facebook); process = false; break; } if (fbFV.Value == (string)friend[FBQueryResult.ID]) { // FacebookIDs are same, definitely a duplicate, do not add process = false; break; } // contact with same name was found but had a different FacebookID, add as a new contact } // add contact if not a duplicate if (process) { var contact = new Item() { ID = Guid.NewGuid(), Name = (string)friend[FBQueryResult.Name], UserID = user.ID, ItemTypeID = SystemItemTypes.Contact, FieldValues = new List<FieldValue>(), }; contact.FieldValues.Add(new FieldValue() { ItemID = contact.ID, FieldName = FieldNames.FacebookID, Value = (string)friend[FBQueryResult.ID] }); contact.FieldValues.Add(new FieldValue() { ItemID = contact.ID, FieldName = FieldNames.Sources, Value = Sources.Facebook }); string jsonContact = JsonSerializer.Serialize(contact); // store the serialized json contact in the value of a new NameValue item in possible contacts list var nameValItem = new Item() { ID = Guid.NewGuid(), Name = (string)friend[FBQueryResult.Name], FolderID = possibleContactsList.FolderID, ParentID = possibleContactsList.ID, UserID = user.ID, ItemTypeID = SystemItemTypes.NameValue, Created = now, LastModified = now, FieldValues = new List<FieldValue>() }; nameValItem.FieldValues.Add(new FieldValue() { FieldName = FieldNames.Value, ItemID = nameValItem.ID, Value = jsonContact }); // add the FacebookID as a fieldvalue on the namevalue item which corresponds to the possible contact, for easier duplicate detection nameValItem.FieldValues.Add(new FieldValue() { FieldName = FieldNames.FacebookID, ItemID = nameValItem.ID, Value = (string)friend[FBQueryResult.ID] }); // add new possible subject to the storage and to the working list of possible contacts userContext.Items.Add(nameValItem); currentPossibleContacts.Add(nameValItem); } } userContext.SaveChanges(); TraceLog.TraceInfo(String.Format("Added {0} possible contacts to list", results.Count)); } catch (Exception ex) { TraceLog.TraceException("Could not retrieve or create a new possible Contact", ex); return false; } return true; }
// get or create a Folder by name for given user public Folder GetOrCreateFolder(User user, string name, Guid itemTypeID) { try { // get the folder by name for user if (Folders.Any(f => f.UserID == user.ID && f.Name == name)) { return Folders.Single(f => f.UserID == user.ID && f.Name == name); } else { // create the folder with given name and itemTypeID for user var folderUser = new FolderUser() { ID = Guid.NewGuid(), FolderID = Guid.NewGuid(), UserID = user.ID, PermissionID = BuiltSteady.Zaplify.Shared.Entities.Permissions.Full }; var folder = new Folder() { ID = folderUser.FolderID, SortOrder = 0, Name = name, UserID = user.ID, ItemTypeID = itemTypeID, Items = new List<Item>(), FolderUsers = new List<FolderUser>() { folderUser } }; Folders.Add(folder); SaveChanges(); TraceLog.TraceInfo(string.Format("Created folder named '{0}' for user '{1}'", name, user.Name)); return folder; } } catch (Exception ex) { TraceLog.TraceException(string.Format("Could not find or create folder named '{0}' for user '{1}'", name, user.Name), ex); return null; } }
public static HttpCookie CreateAuthCookie(User user, out bool renewFBToken) { renewFBToken = false; if (user.ID == Guid.Empty) { // get id from storage to attach to cookie user = LookupUserByName(user.Name, true); // check expiration of facebook consent token, renew if expiring soon if (user.UserCredentials.Any(uc => uc.CredentialType == UserCredential.FacebookConsent)) { UserCredential fbCred = user.UserCredentials.Single<UserCredential>(uc => uc.CredentialType == UserCredential.FacebookConsent); renewFBToken = (fbCred.AccessToken != null && fbCred.AccessTokenExpiration < (DateTime.UtcNow + TimeSpan.FromDays(7))); } } string userData = user.ID.ToString(); if (!string.IsNullOrEmpty(user.Email)) { userData += "|" + user.Email; } FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, user.Name, DateTime.Now, DateTime.Now.AddHours(authTicketLifetime), true, userData); HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)); authCookie.Expires = DateTime.Now.AddHours(authTicketLifetime); return authCookie; }