Exemplo n.º 1
0
        public async Task <ObjectResult <User> > RegisterExternal(RegisterExternalBindingModel model)
        {
            bool registrationOk = false;

            if (!model.InvitationId.HasValue || model.InvitationId == Guid.Empty)
            {
                return(new ObjectResult <User>()
                {
                    IsOk = false,
                    ErrorMessage = "No valid invitation exists"
                });
            }


            // if (model.InvitationId.HasValue)
            {
                using (var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        var userData = await GetFacebookProfileAsync(model.ExternalAccessToken);

                        var fileFullName = string.Empty;
                        if (userData.picture != null)
                        {
                            var picture = GetProfilePicture(userData.picture.data.url);
                            if (picture != null)
                            {
                                fileFullName = Utilities.UploadBlob("profile-images", string.Format("{0}{1}", Guid.NewGuid(), ".jpg"), picture);
                            }
                        }

                        var user = new ApplicationUser
                        {
                            UserName    = model.UserName,
                            Email       = model.UserName,
                            UserProfile = new Authentication.UserProfile()
                            {
                                Id         = Guid.NewGuid(),
                                FirstName  = userData.first_name,
                                LastName   = userData.last_name,
                                MiddleName = userData.middle_name,
                                //ProfileImage = picture,
                                ProfileImageString = fileFullName
                            }
                        };
                        var result = await UserManager.CreateAsync(user);

                        if (result.Succeeded)
                        {
                            var info = new ExternalLoginInfo()
                            {
                                DefaultUserName = model.UserName,
                                Login           = new UserLoginInfo(model.Provider, userData.id)
                            };

                            result = await UserManager.AddLoginAsync(user.Id, info.Login);

                            if (result.Succeeded)
                            {
                                using (InvitationRepository _invitationRepository = new InvitationRepository(Context, user.UserProfile.Id, null))
                                    using (UserContactRepository userContactRepository = new UserContactRepository(Context, user.UserProfile.Id, null))
                                        using (UserProfileRepository userProfileRepository = new UserProfileRepository(Context, user.UserProfile.Id, null))
                                        {
                                            var invitation = _invitationRepository.GetById(model.InvitationId.Value);
                                            if (invitation != null)
                                            {
                                                var role      = DbContext.Roles.First(p => p.Id == invitation.RoleId.ToString());
                                                var addToRole = await this.UserManager.AddToRoleAsync(user.Id, role != null?role.Name : MindCorners.Common.Code.Constants.GeneralUserRoleId);

                                                if (addToRole.Succeeded)
                                                {
                                                    invitation.State     = (int)InvitationStates.Accepted;
                                                    invitation.StateDate = DateTime.Now;
                                                    _invitationRepository.Update(invitation);


                                                    //add userToUserContacts

                                                    userContactRepository.Create(new UserContact()
                                                    {
                                                        ContactName   = user.UserProfile.FullName,
                                                        ContactUserId = user.UserProfile.Id,
                                                        MainUserId    = invitation.CreatorId,
                                                        State         = (int)InvitationStates.Accepted,
                                                        StateDate     = DateTime.Now
                                                    });

                                                    var invitationCreator = userProfileRepository.GetById(invitation.CreatorId);
                                                    userContactRepository.Create(new UserContact()
                                                    {
                                                        ContactName   = invitationCreator.FullName,
                                                        ContactUserId = invitation.CreatorId,
                                                        MainUserId    = user.UserProfile.Id,
                                                        State         = (int)InvitationStates.Accepted,
                                                        StateDate     = DateTime.Now
                                                    });


                                                    //add create Circle of two users
                                                    //var circle = new Common.Model.Circle() { IsGroup = false };
                                                    //CircleRepository circleRepository = new CircleRepository(Context, dbUser, null);
                                                    //circleRepository.Create(circle);
                                                    //Context.SaveChanges();

                                                    //circleRepository.AddMainPersonToCircleUser(circle.Id, dbUser);
                                                    //circleRepository.SynchCircleUsers(circle.Id, new List<Guid>() { userRegistration.UserProfile.Id });

                                                    Context.SaveChanges();

                                                    //_invitationRepository.SaveChanges();
                                                    transactionScope.Complete();
                                                    return(new ObjectResult <User>()
                                                    {
                                                        IsOk = true,
                                                        ReturnedObject = new User()
                                                        {
                                                            FirstName = user.UserProfile.FirstName,
                                                            LastName = user.UserProfile.LastName,
                                                            Email = user.Email,
                                                            FullName = user.UserProfile.FullName,
                                                            Id = user.UserProfile.Id,
                                                            //ProfileImage = applicationUser.UserProfile.ProfileImage,
                                                            ProfileImageString = Request.GetFileUrl((int)FileType.Profile, user.UserProfile.ProfileImageString)
                                                        }
                                                    });
                                                }

                                                return(new ObjectResult <User>()
                                                {
                                                    IsOk = false,
                                                    ErrorMessage = string.Join(",", addToRole.Errors)
                                                });
                                                //   return RedirectToAction("Index", "Home");
                                            }
                                            return(new ObjectResult <User>()
                                            {
                                                IsOk = false,
                                                ErrorMessage = "No valid Invitation"
                                            });
                                        }
                            }
                            return(new ObjectResult <User>()
                            {
                                IsOk = false,
                                ErrorMessage = string.Join(",", result.Errors)
                            });
                        }
                        return(new ObjectResult <User>()
                        {
                            IsOk = false,
                            ErrorMessage = string.Join(",", result.Errors)
                        });
                        //AddErrors(result);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteError(ex);
                        return(new ObjectResult <User>()
                        {
                            IsOk = false,
                            ErrorMessage = ex.ToString()
                        });
                    }
                }
            }

            //if (!ModelState.IsValid)
            //{
            //    return BadRequest(ModelState);
            //}

            //var verifiedAccessToken = await VerifyExternalAccessToken(model.Provider, model.ExternalAccessToken);
            //if (verifiedAccessToken == null)
            //{
            //    return BadRequest("Invalid Provider or External Access Token");
            //}

            //user = new IdentityUser() { UserName = model.UserName };
            //ApplicationUser user = await UserManager.CreateAsync(new UserLoginInfo(model.Provider, model.ExternalAccessToken));

            // bool hasRegistered = user != null;

            // if (hasRegistered)
            // {
            //     return BadRequest("External user is already registered");
            // }

            //// user = new IdentityUser() { UserName = model.UserName };

            // IdentityResult result = await UserManager.CreateAsync(user);
            // if (!result.Succeeded)
            // {
            //     return GetErrorResult(result);
            // }

            // var info = new ExternalLoginInfo()
            // {
            //     DefaultUserName = model.UserName,
            //     Login = new UserLoginInfo(model.Provider, verifiedAccessToken.user_id)
            // };

            // result = await _repo.AddLoginAsync(user.Id, info.Login);
            // if (!result.Succeeded)
            // {
            //     return GetErrorResult(result);
            // }

            // //generate access token response
            // var accessTokenResponse = GenerateLocalAccessTokenResponse(model.UserName);

            // return Ok(accessTokenResponse);



            return(new ObjectResult <User>()
            {
                IsOk = false,
                ErrorMessage = "Error"
            });
        }
Exemplo n.º 2
0
        public async Task <ObjectResult <User> > RegisterUser(UserRegister user)
        {
            if (user.InvitationId == Guid.Empty)
            {
                return(new ObjectResult <User>()
                {
                    IsOk = false,
                    ErrorMessage = "No valid invitation exists"
                });
            }
            using (var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var userRegistration = new ApplicationUser
                    {
                        UserName    = user.Email,
                        Email       = user.Email,
                        UserProfile =
                            new Authentication.UserProfile()
                        {
                            Id        = Guid.NewGuid(),
                            FirstName = user.FirstName,
                            LastName  = user.LastName
                        }
                    };
                    var result = await UserManager.CreateAsync(userRegistration, user.Password);

                    if (result.Succeeded)
                    {
                        var dbUser = userRegistration.UserProfile.Id;
                        using (InvitationRepository _invitationRepository = new InvitationRepository(Context, dbUser, null))
                            using (UserContactRepository userContactRepository = new UserContactRepository(Context, dbUser, null))
                                using (UserProfileRepository userProfileRepository = new UserProfileRepository(Context, dbUser, null))
                                {
                                    var invitation = _invitationRepository.GetById(user.InvitationId);
                                    if (invitation != null)
                                    {
                                        var addToRole =
                                            await
                                            this.UserManager.AddToRoleAsync(userRegistration.Id,
                                                                            MindCorners.Common.Code.Constants.GeneralUserRoleId);

                                        if (addToRole.Succeeded)
                                        {
                                            invitation.State     = (int)InvitationStates.Accepted;
                                            invitation.StateDate = DateTime.Now;
                                            _invitationRepository.Update(invitation);

                                            //add userToUserContacts

                                            userContactRepository.Create(new UserContact()
                                            {
                                                ContactName   = userRegistration.UserProfile.FullName,
                                                ContactUserId = userRegistration.UserProfile.Id,
                                                MainUserId    = invitation.CreatorId,
                                                State         = (int)InvitationStates.Accepted,
                                                StateDate     = DateTime.Now
                                            });

                                            var invitationCreator = userProfileRepository.GetById(invitation.CreatorId);
                                            userContactRepository.Create(new UserContact()
                                            {
                                                ContactName   = invitationCreator.FullName,
                                                ContactUserId = invitation.CreatorId,
                                                MainUserId    = userRegistration.UserProfile.Id,
                                                State         = (int)InvitationStates.Accepted,
                                                StateDate     = DateTime.Now
                                            });

                                            //add create Circle of two users
                                            //var circle = new Common.Model.Circle() { IsGroup = false };
                                            //CircleRepository circleRepository = new CircleRepository(Context, dbUser, null);
                                            //circleRepository.Create(circle);
                                            //Context.SaveChanges();

                                            //circleRepository.AddMainPersonToCircleUser(circle.Id, dbUser);
                                            //circleRepository.SynchCircleUsers(circle.Id, new List<Guid>() { userRegistration.UserProfile.Id });

                                            Context.SaveChanges();

                                            //_invitationRepository.SaveChanges();
                                            transactionScope.Complete();
                                            return(new ObjectResult <User>()
                                            {
                                                IsOk = true,
                                                ReturnedObject = new User()
                                                {
                                                    FirstName = userRegistration.UserProfile.FirstName,
                                                    LastName = userRegistration.UserProfile.LastName,
                                                    Email = userRegistration.Email,
                                                    FullName = userRegistration.UserProfile.FullName,
                                                    Id = userRegistration.UserProfile.Id,
                                                    //ProfileImage = applicationUser.UserProfile.ProfileImage,
                                                    ProfileImageString = Request.GetFileUrl((int)FileType.Profile, userRegistration.UserProfile.ProfileImageString)
                                                }
                                            });
                                        }
                                        return(new ObjectResult <User>()
                                        {
                                            IsOk = false,
                                            ErrorMessage = string.Join(",", addToRole.Errors)
                                        });
                                        //   return RedirectToAction("Index", "Home");
                                    }
                                    return(new ObjectResult <User>()
                                    {
                                        IsOk = false,
                                        ErrorMessage = string.Join(",", result.Errors)
                                    });
                                }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteError(ex);
                    return(new ObjectResult <User>()
                    {
                        IsOk = false,
                        ErrorMessage = ex.ToString()
                    });
                }
                //var user = JsonConvert.DeserializeObject<UserRegister>(userData);
            }

            return(new ObjectResult <User>()
            {
                IsOk = false,
                ErrorMessage = "Error"
            });
        }
Exemplo n.º 3
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                //var ext =
                //    await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
                //var email = ext.Claims.First(x => x.Type.EndsWith("emailaddress")).Value;
                //var name = ext.Claims.First(x => x.Type.EndsWith("name")).Value;
                //var nameIdentifier = ext.Claims.First(x => x.Type.EndsWith("nameidentifier")).Value;


                var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

                //var firstNameClaim = loginInfo.ExternalIdentity.Claims.First(c => c.Type == "urn:facebook:first_name");

                string firstName  = string.Empty;
                string lastName   = string.Empty;
                string middleName = string.Empty;
                string email      = string.Empty;
                byte[] picture    = null;

                if (loginInfo.Login.LoginProvider == "Facebook")
                {
                    var     identity     = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
                    var     access_token = identity.FindFirstValue("FacebookAccessToken");
                    var     fb           = new FacebookClient(access_token);
                    dynamic myInfo       = fb.Get("/me?fields=first_name,middle_name,last_name,id,email,picture.width(600)");
                    // specify the email field
                    loginInfo.Email = myInfo.email;
                    firstName       = myInfo.first_name;
                    middleName      = myInfo.middle_name;
                    lastName        = myInfo.last_name;
                    picture         = GetProfilePicture(GetFacebookImageUrl(myInfo));
                }

                bool registrationOk = false;
                if (InvitationId.HasValue)
                {
                    using (var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                    {
                        try
                        {
                            var fileFullName = string.Empty;
                            if (picture != null)
                            {
                                fileFullName = Utilities.UploadBlob("profile-images", string.Format("{0}{1}", Guid.NewGuid(), ".jpg"), picture);
                            }

                            var user = new ApplicationUser
                            {
                                UserName    = model.Email,
                                Email       = model.Email,
                                UserProfile = new UserProfile()
                                {
                                    Id         = Guid.NewGuid(),
                                    FirstName  = firstName,
                                    LastName   = lastName,
                                    MiddleName = middleName,
                                    //ProfileImage = picture,
                                    ProfileImageString = fileFullName
                                }
                            };
                            var result = await UserManager.CreateAsync(user);

                            if (result.Succeeded)
                            {
                                result = await UserManager.AddLoginAsync(user.Id, info.Login);

                                if (result.Succeeded)
                                {
                                    using (InvitationRepository _invitationRepository = new InvitationRepository(Context, user.UserProfile.Id, null))
                                        using (UserContactRepository userContactRepository = new UserContactRepository(Context, user.UserProfile.Id, null))
                                            using (UserProfileRepository userProfileRepository = new UserProfileRepository(Context, user.UserProfile.Id, null))
                                            {
                                                var invitation = _invitationRepository.GetById(InvitationId.Value);
                                                if (invitation != null)
                                                {
                                                    var role      = DbContext.Roles.First(p => p.Id == invitation.RoleId.ToString());
                                                    var addToRole = await this.UserManager.AddToRoleAsync(user.Id, role != null?role.Name : MindCorners.Common.Code.Constants.GeneralUserRoleId);

                                                    if (addToRole.Succeeded)
                                                    {
                                                        invitation.State     = (int)InvitationStates.Accepted;
                                                        invitation.StateDate = DateTime.Now;
                                                        _invitationRepository.Update(invitation);


                                                        //add userToUserContacts

                                                        userContactRepository.Create(new UserContact()
                                                        {
                                                            ContactName   = user.UserProfile.FullName,
                                                            ContactUserId = user.UserProfile.Id,
                                                            MainUserId    = invitation.CreatorId,
                                                            State         = (int)InvitationStates.Accepted,
                                                            StateDate     = DateTime.Now
                                                        });

                                                        var invitationCreator = userProfileRepository.GetById(invitation.CreatorId);
                                                        userContactRepository.Create(new UserContact()
                                                        {
                                                            ContactName   = invitationCreator.FullName,
                                                            ContactUserId = invitation.CreatorId,
                                                            MainUserId    = user.UserProfile.Id,
                                                            State         = (int)InvitationStates.Accepted,
                                                            StateDate     = DateTime.Now
                                                        });


                                                        //add create Circle of two users
                                                        //var circle = new Common.Model.Circle() { IsGroup = false };
                                                        //CircleRepository circleRepository = new CircleRepository(Context, dbUser, null);
                                                        //circleRepository.Create(circle);
                                                        //Context.SaveChanges();

                                                        //circleRepository.AddMainPersonToCircleUser(circle.Id, dbUser);
                                                        //circleRepository.SynchCircleUsers(circle.Id, new List<Guid>() { userRegistration.UserProfile.Id });

                                                        Context.SaveChanges();

                                                        //_invitationRepository.SaveChanges();
                                                        transactionScope.Complete();
                                                    }
                                                    registrationOk = true;
                                                }
                                            }
                                }
                                if (registrationOk)
                                {
                                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                                    return(RedirectToAction("Index", "Home"));
                                }
                            }

                            AddErrors(result);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteError(ex);
                        }
                    }

                    //var user = new ApplicationUser
                    //{
                    //    UserName = model.Email,
                    //    Email = model.Email,
                    //    UserProfile = new UserProfile()
                    //    {
                    //        Id = Guid.NewGuid(),
                    //        FirstName = firstName,
                    //        LastName = lastName,
                    //        MiddleName = middleName,
                    //        ProfileImage = picture,
                    //    }
                    //};
                    //var result = await UserManager.CreateAsync(user);
                    //if (result.Succeeded)
                    //{
                    //    result = await UserManager.AddLoginAsync(user.Id, info.Login);
                    //    if (result.Succeeded)
                    //    {
                    //        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                    //        return RedirectToLocal(returnUrl);
                    //    }
                    //}
                }
            }
            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }