// GET api/EqualConnections public HttpResponseMessage Post(UserComparisonRequestDTO parameters) { Services.Log.Info("EqualConnectionsController entered!"); MobileServiceContext context = new MobileServiceContext(); List<BasicUserInfoDTO> equal = new List<BasicUserInfoDTO>(); List<Account> userConnections = context.ConnectRequests.Where(cr => cr.Accepted.Value && (cr.RequestUserId == parameters.UserId || cr.ConnectUserId == parameters.UserId)).Select(cr => ((cr.ConnectUserId == parameters.UserId) ? cr.RequestUser : cr.ConnectUser)).ToList(); List<Account> user2Connections = context.ConnectRequests.Where(cr => cr.Accepted.Value && (cr.RequestUserId == parameters.CompUserId || cr.ConnectUserId == parameters.CompUserId)).Select(cr => ((cr.ConnectUserId == parameters.CompUserId) ? cr.RequestUser : cr.ConnectUser)).ToList(); IEnumerable<Account> intersect = userConnections.Intersect<Account>(user2Connections); foreach (Account account in intersect) { if (account != null) { BasicUserInfoDTO userInfo = new BasicUserInfoDTO(); userInfo.AccountId = account.Id; UserInfo ui = context.UserInfos.First(uinfo => uinfo.UserId == account.Id); userInfo.Age = ui.Age; userInfo.Status = ui.About; userInfo.Username = account.Username; userInfo.FirstName = ui.FirstName; userInfo.LastName = ui.LastName; userInfo.ProfilePicUrl = ui.ProfilePicUrl; equal.Add(userInfo); } } return this.Request.CreateResponse(HttpStatusCode.OK, equal); }
// POST api/CustomLogin public HttpResponseMessage Post(LoginRequest loginRequest) { MobileServiceContext context = new MobileServiceContext(); Account account = context.Accounts.SingleOrDefault(a => a.Username == loginRequest.username); if (account != null) { byte[] incoming = LoginProviderUtil .hash(loginRequest.password, account.Salt); if (LoginProviderUtil.slowEquals(incoming, account.SaltedAndHashedPassword)) { ClaimsIdentity claimsIdentity = new ClaimsIdentity(); claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, loginRequest.username)); LoginResult loginResult = new CustomLoginProvider(handler) .CreateLoginResult(claimsIdentity, Services.Settings.MasterKey); var customLoginResult = new CustomLoginResult() { AccountId = account.Id, UserId = loginResult.User.UserId, username = account.Username, MobileServiceAuthenticationToken = loginResult.AuthenticationToken }; return this.Request.CreateResponse(HttpStatusCode.OK, customLoginResult); } } return this.Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid username or password"); }
// Post api/GetUserInfo public FullUserInfoDTO Post(AccountId accountid) { MobileServiceContext context = new MobileServiceContext(); FullUserInfoDTO userinfo = new FullUserInfoDTO(); userinfo.AccountId = accountid.accountid; Account a = context.Accounts.FirstOrDefault(x => x.Id == accountid.accountid); if (a.FacebookId != null) { userinfo.FacebookProfileLink = "https://facebook.com/" + a.FacebookId; userinfo.FacebookConnected = true; } else { userinfo.FacebookConnected = false; } if (a.LinkedInId != null) { userinfo.LinkedInProfileLink = "http://www.linkedin.com/profile/view?id=" + a.LinkedInId; userinfo.LinkedInConnected = true; } else { userinfo.LinkedInConnected = false; } if (!context.UserInfos.Any(uinfo => uinfo.UserId == accountid.accountid)) { context.UserInfos.Add(new UserInfo() { Id = Guid.NewGuid().ToString(), Bio = "About me", UserId = accountid.accountid }); context.SaveChanges(); } UserInfo ui = context.UserInfos.Include("Account").First(uinfo => uinfo.UserId == accountid.accountid); userinfo.UserInfoId = ui.Id; userinfo.Age = ui.Age; userinfo.Status = ui.Bio; userinfo.About = ui.About; userinfo.Gender = ui.Gender; userinfo.Username = ui.Account.Username; userinfo.FirstName = ui.FirstName; userinfo.LastName = ui.LastName; userinfo.ProfilePicUrl = ui.ProfilePicUrl; userinfo.BusinessInterested = a.BusinessInterest; userinfo.PrivateInterested = a.PrivateInterest; UserContact userContact = context.UserContacts.FirstOrDefault(contact => contact.UserId == accountid.accountid); if(userContact != null) { userinfo.PhoneNr = userContact.PhoneNr; userinfo.Email = userContact.Email; } return userinfo; }
// POST api/ConnectedUsers public HttpResponseMessage Post(AccountId accountid) { MobileServiceContext context = new MobileServiceContext(); if(accountid == null) return this.Request.CreateResponse(HttpStatusCode.NotFound); string requesterId = accountid.accountid; List<BasicUserInfoDTO> response = new List<BasicUserInfoDTO>(); foreach (ConnectRequest connRequests in context.ConnectRequests.Where(x => x.Accepted == true && (x.RequestUserId == requesterId || x.ConnectUserId == requesterId))) { response.Add(UserInfoService.GetBasicUserInfo((connRequests.ConnectUserId != requesterId) ? connRequests.ConnectUserId: connRequests.RequestUserId)); } return this.Request.CreateResponse(HttpStatusCode.OK, response); }
// POST api/ParticipateEvent public HttpResponseMessage Post(ParticipateEventRequest requestData) { MobileServiceContext context = new MobileServiceContext(); if(requestData == null ||requestData.eventid == null) return this.Request.CreateResponse(HttpStatusCode.NotFound); Event evt = context.Events.Include("Accounts").FirstOrDefault(e => e.Id == requestData.eventid); List<BasicUserInfoDTO> participators = new List<BasicUserInfoDTO>(); foreach(Account a in evt.Accounts) { participators.Add(UserInfoService.GetBasicUserInfo(a.Id)); } return this.Request.CreateResponse(HttpStatusCode.OK, participators); }
// POST api/CustomRegistration public HttpResponseMessage Post(RegistrationRequest registrationRequest) { if (!Regex.IsMatch(registrationRequest.username, "^[a-zA-Z0-9]{4,}$")) { return this.Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid username (at least 4 chars, alphanumeric only)"); } else if (registrationRequest.password.Length < 8) { return this.Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid password (at least 8 chars required)"); } MobileServiceContext context = new MobileServiceContext(); Account account; try { account = context.Accounts.Where(a => a.Username == registrationRequest.username).SingleOrDefault(); } catch(Exception e) { Console.WriteLine(e.StackTrace); return this.Request.CreateResponse(HttpStatusCode.InternalServerError); } if (account != null) { return this.Request.CreateResponse(HttpStatusCode.BadRequest, "That username already exists."); } else { byte[] salt = LoginProviderUtil.generateSalt(); Account newAccount = new Account { Id = Guid.NewGuid().ToString(), Username = registrationRequest.username, Salt = salt, SaltedAndHashedPassword = LoginProviderUtil.hash(registrationRequest.password, salt) }; context.Accounts.Add(newAccount); context.SaveChanges(); UserInfo newUserInfo; context.UserInfos.Add(newUserInfo = new UserInfo() { Bio = "About me", UserId = newAccount.Id, Id = Guid.NewGuid().ToString() }); context.SaveChanges(); return this.Request.CreateResponse(HttpStatusCode.Created); } }
// Post api/FBGetProfile public async Task<HttpResponseMessage> Post(AccountId accountid) { HttpStatusCode httpStatus = HttpStatusCode.OK; MobileServiceContext context = new MobileServiceContext(); ServiceUser user = this.User as ServiceUser; if (user == null) { throw new InvalidOperationException("This can only be called by authenticated clients"); } FacebookCredentials creds = (await user.GetIdentitiesAsync()).OfType<FacebookCredentials>().FirstOrDefault(); if (creds != null) { var fbDataProvider = new FBProfileDataProvider(creds.AccessToken); Network facebook = context.Networks.First(n => n.Id == (Int16)NetworkType.FACEBOOK); ProfileData fbProfileData = await fbDataProvider.GetUserInfo(); UserInfo userInfo; if (context.UserInfos.Any(ui => ui.UserId == accountid.accountid)) { userInfo = context.UserInfos.Include("UserInfoDetail").First(ui => ui.UserId == accountid.accountid); userInfo.Bio = fbProfileData.Bio; userInfo.About = fbProfileData.About; userInfo.ProfilePicUrl = fbProfileData.ProfilePicUrl; // TODO: Update other propoerties UserInfoDetail detail = userInfo.UserInfoDetails.First(x => x.NetworkId == facebook.Id); if (detail == null) { detail = new UserInfoDetail() { JsonInfo = fbProfileData.AsJsonString(), NetworkId = facebook.Id }; userInfo.UserInfoDetails.Add(detail); } else detail.JsonInfo = fbProfileData.AsJsonString(); } else { userInfo = new UserInfo() { UserId = accountid.accountid }; userInfo.SetProfileInfo(fbProfileData); userInfo.Id = Guid.NewGuid().ToString(); userInfo.UserInfoDetails.Add(new UserInfoDetail() { JsonInfo = fbProfileData.AsJsonString() }); context.UserInfos.Add(userInfo); } context.SaveChanges(); httpStatus = HttpStatusCode.Created; return this.Request.CreateResponse(httpStatus, userInfo); } throw new Exception("Facebook identity not found"); }
public static BasicUserInfoDTO GetBasicUserInfo(string userId) { MobileServiceContext context = new MobileServiceContext(); BasicUserInfoDTO userInfo = new BasicUserInfoDTO(); userInfo.AccountId = userId; UserInfo ui = context.UserInfos.Include("Account").Include("UserInfoDetails").First(uinfo => uinfo.UserId == userId); userInfo.Age = (userInfo.Age == null) ? ui.Age : userInfo.Age; userInfo.Status = ui.Bio; userInfo.About = ui.About; userInfo.FacebookConnected = (userInfo.FacebookConnected || ui.UserInfoDetails.Any(x => x.NetworkId == (Int16)NetworkType.FACEBOOK)) ? true : false; userInfo.Gender = (userInfo.Gender == null) ? ui.Gender : userInfo.Gender; userInfo.Username = (userInfo.Username == null) ? ui.Account.Username : userInfo.Username; userInfo.FirstName = (userInfo.FirstName == null) ? ui.FirstName : userInfo.FirstName; userInfo.LastName = (userInfo.LastName == null) ? ui.LastName : userInfo.LastName; userInfo.ProfilePicUrl = (userInfo.ProfilePicUrl == null) ? ui.ProfilePicUrl : userInfo.ProfilePicUrl; return userInfo; }
// POST api/UnseenComparisons public HttpResponseMessage Post(UnseenComparisonsRequestDTO requestData) { Services.Log.Info("Entered UnseenComparisons!"); MobileServiceContext context = new MobileServiceContext(); List<UserComparisonResultDTO> result = new List<UserComparisonResultDTO>(); List<UserComparison> comps = context.UserComparisons.Include("User").Include("CompUser") .Where(x => (x.UserId == requestData.UserId || x.CompUserId == requestData.UserId)).OrderByDescending(x => x.CreatedAt).ToList(); foreach (UserComparison cmp in comps) { bool currentUserIsInitiator = true; //Initiator of past comparison Account otherUser; if (cmp.CompUserId == requestData.UserId) { currentUserIsInitiator = false; otherUser = cmp.User; } else { otherUser = cmp.CompUser; } if (!result.Any(x => (x.UserId == otherUser.Id))) { if (!context.ConnectRequests.Any(connectReqeust => ((connectReqeust.ConnectUserId == requestData.UserId && connectReqeust.RequestUserId == otherUser.Id) || (connectReqeust.ConnectUserId == otherUser.Id && connectReqeust.RequestUserId == requestData.UserId)) && connectReqeust.Accepted != null)){ result.Add(new UserComparisonResultDTO() { UserId = otherUser.Id, UserName = otherUser.Username, EqualData = cmp.EqualJson, Date = cmp.CreatedAt, CurrentUserWasInitiator = currentUserIsInitiator, ProfilePic = context.UserInfos.FirstOrDefault(x => x.UserId == otherUser.Id).ProfilePicUrl }); } } } return this.Request.CreateResponse(HttpStatusCode.OK, result); }
// POST api/CompareUsers public HttpResponseMessage Post(UserComparisonRequestDTO userComparisonRequest) { Services.Log.Info("Entered CompareUsers!"); MobileServiceContext context = new MobileServiceContext(); UserComparison lastUserComparison = context.UserComparisons.Where(x => (x.UserId == userComparisonRequest.UserId && x.CompUserId == userComparisonRequest.CompUserId) || (x.UserId == userComparisonRequest.CompUserId && x.CompUserId == userComparisonRequest.UserId)).OrderByDescending(x => x.CreatedAt).FirstOrDefault(); //if(lastUserComparison != null) //{ // if(!context.UserInfos.Any(x => x.UserId == userComparisonRequest.UserId && x.UpdatedAt > lastUserComparison.CreatedAt) && // !context.UserInfos.Any(x => x.UserId == userComparisonRequest.UserId && x.UpdatedAt > lastUserComparison.CreatedAt)) // { // //No Profile changes since last update // return this.Request.CreateResponse(HttpStatusCode.OK, lastUserComparison); // } //} if (userComparisonRequest.CompareObjects == null) userComparisonRequest.CompareObjects = ProfileData.GetAllProfileDataObjects(); UserInfo userInfo = context.UserInfos.Include("UserInfoDetails").FirstOrDefault(uiDet => uiDet.UserId == userComparisonRequest.UserId); UserInfo compUserInfo = context.UserInfos.Include("UserInfoDetails").FirstOrDefault(uiDet => uiDet.UserId == userComparisonRequest.CompUserId); UserInfoDetail mergedUserInfo = JsonUtil.MergeUserInfoDetails(userInfo.UserInfoDetails); UserInfoDetail mergedCompUserInfo = JsonUtil.MergeUserInfoDetails(compUserInfo.UserInfoDetails); UserComparison userComp = ProfileComparisonUtil.CompareUserProfiles(JsonConvert.DeserializeObject<ProfileData>(mergedUserInfo.JsonInfo), JsonConvert.DeserializeObject<ProfileData>(mergedCompUserInfo.JsonInfo), userComparisonRequest.CompareObjects); userComp.Id = Guid.NewGuid().ToString(); userComp.UserId = userComparisonRequest.UserId; userComp.CompUserId = userComparisonRequest.CompUserId; context.UserComparisons.Add(userComp); context.SaveChanges(); Services.Log.Info("CompareUsers finished"); return this.Request.CreateResponse(HttpStatusCode.OK, userComp); }
// POST api/FBConnectUser public async System.Threading.Tasks.Task<HttpResponseMessage> Get(NetworkType providerType) { ServiceUser user = this.User as ServiceUser; HttpStatusCode httpStatus = HttpStatusCode.OK; MobileServiceContext context = new MobileServiceContext(); Account account = null; ProviderCredentials creds = null; bool firstLogin = false; if (providerType == NetworkType.FACEBOOK) { creds = (await user.GetIdentitiesAsync()).OfType<FacebookCredentials>().FirstOrDefault(); if (creds != null) { account = context.Accounts.FirstOrDefault(a => a.FacebookId == creds.UserId); if(account == null) { firstLogin = true; account = new Account() { Id = Guid.NewGuid().ToString(), Username = "******", FacebookId = creds.UserId }; context.Accounts.Add(account); UserInfo newUserInfo; context.UserInfos.Add(newUserInfo = new UserInfo() { UserId = account.Id, Id = Guid.NewGuid().ToString() }); context.SaveChanges(); httpStatus = HttpStatusCode.Created; } } } if (providerType == NetworkType.LINKED_IN) { creds = (await user.GetIdentitiesAsync()).OfType<LinkedInCredentials>().FirstOrDefault(); if (creds != null) { account = context.Accounts.FirstOrDefault(a => a.LinkedInId == creds.UserId); if (account == null) { firstLogin = true; account = new Account() { Id = Guid.NewGuid().ToString(), Username = "******", LinkedInId = creds.UserId }; context.Accounts.Add(account); UserInfo newUserInfo; context.UserInfos.Add(newUserInfo = new UserInfo() { UserId = account.Id, Id = Guid.NewGuid().ToString() }); context.SaveChanges(); httpStatus = HttpStatusCode.Created; } } } if (account != null) { var customLoginResult = new ProviderLoginResult() { AccountId = account.Id, username = account.Username, FirstLogin = firstLogin }; return this.Request.CreateResponse(httpStatus, customLoginResult); } return this.Request.CreateResponse(httpStatus); }
// POST api/FindUsers public HttpResponseMessage Post(FindUsersRequestData requestData) { MobileServiceContext context = new MobileServiceContext(); Account requester = context.Accounts.FirstOrDefault(x => x.Id == requestData.UserId); if (requester == null) { Services.Log.Error("User with id from param is not available"); return this.Request.CreateResponse(HttpStatusCode.BadRequest); } bool checkLocation = requestData.MaxDistance > 0 && (requestData.Latitude != 0 || requestData.Longitude != 0); if (checkLocation) { DateTimeOffset fiveHoursBefore = DateTimeOffset.Now.AddHours(-500); List<UserContext> uContexts = context.UserContexts.ToList(); uContexts = uContexts.Where(x => DateTimeOffset.Compare(x.CreatedAt.Value, fiveHoursBefore) > 0).GroupBy(uContext => uContext.AccountRefId).Select(grp => grp.First()).OrderBy(x => x.CreatedAt).ToList(); uContexts.RemoveAll(ctx => ctx.AccountRefId == requestData.UserId); uContexts.RemoveAll(ctx => !((requester.BusinessInterest && ctx.Account.BusinessInterest) || (requester.PrivateInterest && ctx.Account.PrivateInterest))); if (requestData.AlreadyCompared.HasValue) { uContexts.RemoveAll(ctx => { return !requestData.AlreadyCompared.Value == context.UserComparisons.Any(comp => (comp.UserId == requestData.UserId || comp.UserId == ctx.AccountRefId) && (comp.CompUserId == requestData.UserId || comp.CompUserId == ctx.AccountRefId)); }); } DbGeography georaphy = DBGeographyUtil.getDBGeography(requestData.Longitude, requestData.Latitude); uContexts.RemoveAll(ctx => ctx.Location.Distance(georaphy) > requestData.MaxDistance); List<BasicUserInfoDTO> response = uContexts.Select(ucont => { try { BasicUserInfoDTO userInfo = UserInfoService.GetBasicUserInfo(ucont.AccountRefId); return userInfo; } catch (Exception e) { Console.Write(e.Message); return null; } } ).ToList(); return this.Request.CreateResponse(HttpStatusCode.OK, response); } else { List<BasicUserInfoDTO> response = new List<BasicUserInfoDTO>(); List<UserComparison> allComparisons = context.UserComparisons.ToList(); foreach (Account a in context.Accounts.Where(a => a.Id != requestData.UserId)) { if (!requestData.AlreadyCompared.HasValue || requestData.AlreadyCompared.Value == allComparisons.Any(comp => (comp.UserId == requestData.UserId || comp.UserId == a.Id) && (comp.CompUserId == requestData.UserId || comp.CompUserId == a.Id))) if ((requester.BusinessInterest && a.BusinessInterest) || (requester.PrivateInterest && a.PrivateInterest)) response.Add(UserInfoService.GetBasicUserInfo(a.Id)); } return this.Request.CreateResponse(HttpStatusCode.OK, response); } }
// Post api/SyncInconsistentProfile public async Task<HttpResponseMessage> Post(SyncInconsistentProfileRequest requestParams) { HttpStatusCode httpStatus = HttpStatusCode.OK; MobileServiceContext context = new MobileServiceContext(); ServiceUser user = this.User as ServiceUser; //Todo first userInfo is Empty if (user == null) { throw new InvalidOperationException("This can only be called by authenticated clients"); } Account account = context.Accounts.FirstOrDefault(a => a.Id == requestParams.accountid); UserInfo userInfo = context.UserInfos.Include("UserInfoDetails").FirstOrDefault(ui => ui.UserId == requestParams.accountid); if (requestParams.provider == 0 || requestParams.provider == 1) { FacebookCredentials creds = (await user.GetIdentitiesAsync()).OfType<FacebookCredentials>().FirstOrDefault(); if (creds != null) { ETLProfileDataProvider dataProvider = new FBProfileDataProvider(creds.AccessToken); ProfileData fbProfileData = await dataProvider.GetUserInfo(); var detail = (userInfo != null) ? userInfo.UserInfoDetails.FirstOrDefault(x => x.NetworkId == (int)NetworkType.FACEBOOK): new UserInfoDetail(); if(detail == null) detail = new UserInfoDetail() { Id = Guid.NewGuid().ToString() }; detail.JsonInfo = fbProfileData.AsJsonString(); detail.SetNetork(context.Networks.First(n => n.Id == (int)NetworkType.FACEBOOK)); if(userInfo == null) { userInfo = new UserInfo(); userInfo.Id = Guid.NewGuid().ToString(); } userInfo.SetProfileInfo(fbProfileData); if(userInfo.UserInfoDetails != null && !userInfo.UserInfoDetails.Any(x => x.NetworkId == (int)NetworkType.FACEBOOK)) userInfo.UserInfoDetails.Add(detail); account.FacebookId = creds.UserId; context.SaveChanges(); httpStatus = HttpStatusCode.Created; } } if(requestParams.provider == 0 || requestParams.provider == 2) { LinkedInCredentials creds = (await user.GetIdentitiesAsync()).OfType<LinkedInCredentials>().FirstOrDefault(); if (creds != null) { ETLProfileDataProvider dataProvider = new LinkedInProfileDataProvider(creds.AccessToken); ProfileData linkedInProfileData = await dataProvider.GetUserInfo(); var detail = (userInfo != null) ? userInfo.UserInfoDetails.FirstOrDefault(x => x.NetworkId == (int)NetworkType.LINKED_IN): new UserInfoDetail(); if (detail == null) detail = new UserInfoDetail() { Id = Guid.NewGuid().ToString() }; detail.JsonInfo = linkedInProfileData.AsJsonString(); detail.SetNetork(context.Networks.First(n => n.Id == (int)NetworkType.LINKED_IN)); if (userInfo == null) { userInfo = new UserInfo(); userInfo.Id = Guid.NewGuid().ToString(); } userInfo.SetProfileInfo(linkedInProfileData); if (userInfo.UserInfoDetails != null && !userInfo.UserInfoDetails.Any(x => x.NetworkId == (int)NetworkType.LINKED_IN)) userInfo.UserInfoDetails.Add(detail); account.LinkedInId = creds.UserId; context.SaveChanges(); httpStatus = HttpStatusCode.Created; } } return this.Request.CreateResponse(httpStatus, userInfo); }