示例#1
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider;
            string providerUserId;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Добавление нового пользователя в базу данных
                using (var db = new UsersContext())
                {
                    UserProfile user =
                        db.UserProfiles.FirstOrDefault(
                            u => string.Equals(u.UserName, model.UserName, StringComparison.CurrentCultureIgnoreCase));
                    // Проверка наличия пользователя в базе данных
                    if (user == null)
                    {
                        // Добавление имени в таблицу профиля
                        db.UserProfiles.Add(new UserProfile {
                            UserName = model.UserName
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }

                    ModelState.AddModelError("UserName", Resources.UserNameNotExists);
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
示例#2
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile {
                            UserName = model.UserName
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
示例#3
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Добавление нового пользователя в базу данных
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Проверка наличия пользователя в базе данных
                    if (user == null)
                    {
                        // Добавление имени в таблицу профиля
                        db.UserProfiles.Add(new UserProfile {
                            UserName = model.UserName
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "Имя пользователя уже существует. Введите другое имя пользователя.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // 将新用户插入到数据库
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // 检查用户是否已存在
                    if (user == null)
                    {
                        // 将名称插入到配置文件表
                        db.UserProfiles.Add(new UserProfile {
                            UserName = model.UserName
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "用户名已存在。请输入其他用户名。");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
        public ActionResult ExternalLoginConfirmationCustom(RegisterExternalLoginModel model)
        {
            string provider       = null;
            string providerUserId = null;

            provider       = model.ExternalLoginData.Split('|')[0];
            providerUserId = model.ExternalLoginData.Split('|')[1];

            if (ModelState.IsValid)
            {
                // Insertar un nuevo usuario en la base de datos
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Comprobar si el usuario ya existe
                    if (user == null)
                    {
                        // Insertar el nombre en la tabla de perfiles
                        db.UserProfiles.Add(new UserProfile {
                            UserName = model.UserName
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        Roles.AddUserToRole(model.UserName, "Usuario");
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToAction("index", "home"));
                    }
                    else
                    {
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
                        return(RedirectToAction("index", "home"));
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = Url.Action("index", "home");
            return(View(model));
        }
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Insertar un nuevo usuario en la base de datos
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Comprobar si el usuario ya existe
                    if (user == null)
                    {
                        // Insertar el nombre en la tabla de perfiles
                        db.UserProfiles.Add(new UserProfile {
                            UserName = model.UserName
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "El nombre de usuario ya existe. Escriba un nombre de usuario diferente.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Insérer un nouvel utilisateur dans la base de données
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Vérifier si l'utilisateur n'existe pas déjà
                    if (user == null)
                    {
                        // Insérer le nom dans la table des profils
                        db.UserProfiles.Add(new UserProfile {
                            UserName = model.UserName
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "Le nom d'utilisateur existe déjà. Entrez un nom d'utilisateur différent.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
示例#8
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            FacebookClient2017.RewriteRequest();
            var regClients = OAuthWebSecurity.RegisteredClientData;
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

            if (!result.IsSuccessful)
            {
                return(RedirectToAction("ExternalLoginFailure"));
            }

            // Check database for entry for provider, userid
            var oAuthResult = MembershipService.ValidateOAuthUser(result, this.Session);

            if (oAuthResult.AccountLinked)
            {
                //Log the user in
                this.ValidateUser(oAuthResult.UserEmail, oAuthResult.HashedPassword);

                return(RedirectToLocal(returnUrl));
            }

            //If account not already linked, then link them to the currently authenticated and logged in user
            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return(RedirectToLocal(returnUrl));
            }
            else
            {
                //User needs to register for a rooster account, direct them to registration process.
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl           = returnUrl;
                ViewBag.StatesList          = WebUI.Common.Common.GetStates();
                return(View("ExternalLoginConfirmation", new RegisterModelDTO {
                    ExternalLoginData = loginData
                }));
            }
        }
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            string callbackUrl = this.Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl });
            var    result      = OAuthWebSecurity.VerifyAuthentication(callbackUrl);

            if (!result.IsSuccessful)
            {
                return(this.RedirectToAction("ExternalLoginFailure"));
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, this.Config.CreatePersistentCookie))
            {
                string username = OAuthWebSecurity.GetUserName(result.Provider, result.ProviderUserId);
                return(this.PostSuccessfulLogin(username, returnUrl));
            }

            if (this.User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, this.User.Identity.Name);
                string username = OAuthWebSecurity.GetUserName(result.Provider, result.ProviderUserId);
                return(this.PostSuccessfulLogin(username, returnUrl));
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                this.ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                this.ViewBag.ReturnUrl           = returnUrl;

                var registrationModel = new ExternalLoginRegistrationModel <TUserProfileViewModel>
                {
                    UserProfileViewModel = new TUserProfileViewModel(),
                    ExternalLoginData    = loginData
                };
                registrationModel.UserProfileViewModel.Username = result.UserName;

                return(this.View("ExternalLoginConfirmation", registrationModel));
            }
        }
示例#10
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            this.ViewBag.HideNavigationLinks = true;
            this.ViewBag.HideLoginSection    = true;

            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(this.Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

            if (!result.IsSuccessful)
            {
                return(this.RedirectToAction("ExternalLoginFailure"));
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return(this.RedirectToLocal(returnUrl));
            }

            if (this.User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, this.User.Identity.Name);
                return(this.RedirectToLocal(returnUrl));
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                this.ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                this.ViewBag.ReturnUrl           = returnUrl;
                var model = new RegisterExternalLoginModel
                {
                    UserName          = result.UserName,
                    ExternalLoginData = loginData,
                    FB_name           = result.ExtraData.ContainsKey("name") ? result.ExtraData["name"] : string.Empty,
                    FB_link           = result.ExtraData.ContainsKey("link") ? result.ExtraData["link"] : string.Empty,
                    GL_email          = result.ExtraData.ContainsKey("email") ? result.ExtraData["email"] : string.Empty
                };
                return(View("ExternalLoginConfirmation", model));
            }
        }
        public ActionResult ExternalLoginConfirmation(ExternalLoginRegistrationModel <TUserProfileViewModel> registrationModel, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (this.User.Identity.IsAuthenticated ||
                !OAuthWebSecurity.TryDeserializeProviderUserId(registrationModel.ExternalLoginData, out provider, out providerUserId))
            {
                return(this.RedirectToAction("Manage"));
            }

            if (this.ModelState.IsValid)
            {
                //// Insert a new user into the database

                var profile = this.Repository.GetByUsername(registrationModel.UserProfileViewModel.Username);

                // Check if user already exists
                if (profile == null)
                {
                    profile = this.CreateUserProfile(registrationModel.UserProfileViewModel);

                    OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, profile.Username);
                    OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                    return(this.PostSuccessfulLogin(profile.Username, returnUrl));
                }
                else
                {
                    this.ModelState.AddModelError(
                        Of <TUserProfileViewModel> .CodeNameFor(m => m.Username),
                        "User name already exists. Please enter a different user name.");
                }
            }

            this.ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            this.ViewBag.ReturnUrl           = returnUrl;
            return(this.View(registrationModel));
        }
示例#12
0
        //[ValidateAntiForgeryToken]
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider;
            string providerUserId;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (var db = new EStudyBaseContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile {
                            UserName = model.UserName, Email = "*****@*****.**"
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }

                    ModelState.AddModelError("UserName", "Bu kullanıcı adı ile daha önceden kayıt oluşturulmuş. Lütfen farklı bir kullanıcı adı giriniz.");
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
示例#13
0
        public async Task <ActionResult> OAuthLoginCallback(string returnUrl, CancellationToken cancellationToken)
        {
            OAuth.OAuthGoogleClient.RewriteRequest();

            var result = OAuthWebSecurity.VerifyAuthentication(Url.Action("oauthlogincallback", new RouteValueDictionary {
                { "returnurl", returnUrl }
            }));

            if (!result.IsSuccessful)
            {
                return(RedirectToAction("OAuthLoginFailure"));
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                string userName = OAuthWebSecurity.GetUserName(result.Provider, result.ProviderUserId);
                await UpdateUserLoginDataAsync(userName, cancellationToken);

                return(RedirectToLocal(returnUrl));
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account.
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return(RedirectToLocal(returnUrl));
            }
            else
            {
                // User is new, ask for their desired membership name.
                string extraData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl           = returnUrl;
                var model = CreateSignupInfo(result.ExtraData);
                model.ExtraData = extraData;
                return(View("OAuthLoginConfirmation", model));
            }
        }
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new
            {
                ReturnUrl
                    =
                        returnUrl
            }));

            if (!result.IsSuccessful)
            {
                return(RedirectToAction("ExternalLoginFailure"));
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return(RedirectToLocal(returnUrl));
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return(RedirectToLocal(returnUrl));
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl           = returnUrl;
                return(View("ExternalLoginConfirmation", new RegisterExternalLoginModel
                {
                    UserName = result.UserName,
                    ExternalLoginData = loginData
                }));
            }
        }
        public virtual ActionResult ExternalLoginConfirmation(RegisterExternalLoginViewModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction(MVC.Account.Manage()));
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                User user = _dbContext.Users.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                // Check if user already exists
                if (user == null)
                {
                    // Insert name into the profile table
                    _dbContext.Users.Add(new User {
                        UserName = model.UserName
                    });
                    _dbContext.SaveChanges();

                    OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                    OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                    return(RedirectToLocal(returnUrl));
                }
                else
                {
                    ModelState.AddModelError("Email", "Email already in use. Please either login with existing account or use a different email address.");
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
示例#16
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                var user = this._userRepository.GetUserByUserName(model.UserName);

                // if does not have any user with this username
                if (user == null)
                {
                    _userRepository.CreateUser(
                        model.UserName,
                        model.UserName,
                        "".GetDefaultPassword(),
                        "".GetDefaultEmail(),
                        (int)Role.RegisterUser,
                        "".GetDefaultCreatedByUser());

                    OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                    OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                    return(RedirectToLocal(returnUrl));
                }

                this.ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
示例#17
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                var userId = WebSecurity.GetUserId(model.UserName);
                if (userId == -1)
                {
                    string str = ConfigurationManager.ConnectionStrings["mongodb"].ConnectionString;
                    DefaultUsersService service = new DefaultUsersService(str);
                    SampleUserProfile   profile = new SampleUserProfile();
                    profile.UserName = model.UserName;
                    service.Save(profile);

                    OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                    OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                    return(RedirectToLocal(returnUrl));
                }
                else
                {
                    ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
示例#18
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

            if (!result.IsSuccessful)
            {
                return(RedirectToAction("ExternalLoginFailure"));
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return(RedirectToLocal(returnUrl));
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return(RedirectToLocal(returnUrl));
            }
            else
            {
                // User is new, redirect to external registration chooser (login-existing or register)
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ExternalLoginCallbackModel model = new ExternalLoginCallbackModel
                {
                    ProviderName      = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName,
                    ExternalLoginData = loginData,
                    ProviderUserId    = result.ProviderUserId,
                    ProviderUserName  = result.UserName,
                    ProviderEMail     = result.UserName,
                    ReturnUrl         = returnUrl
                };
                return(View(model));
            }
        }
示例#19
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                var user = _userService.Users.FirstOrDefault(x => x.Name.ToLower() == model.UserName.ToLower());

                if (user == null)
                {
                    _userService.AddUser(new User
                    {
                        Name = model.UserName
                    });

                    OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                    OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                    return(RedirectToLocal(returnUrl));
                }
                else
                {
                    ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
示例#20
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

            if (!result.IsSuccessful)
            {
                return(RedirectToAction("ExternalLoginFailure"));
            }


            // store the user id in the session
            Session["UserFacebookId"] = result.ProviderUserId;
            webpages_OAuthMembership userrecord = db.webpages_OAuthMembership.FirstOrDefault(m => m.Provider == "facebook" && m.ProviderUserId == result.ProviderUserId);

            if (userrecord != null)
            {
                Session["UserID"] = userrecord.UserId;
            }


            // remember the user's facebook friends

            var     fb     = new FacebookClient(result.ExtraData["accesstoken"]);
            dynamic myInfo = fb.Get("/me/friends");

            foreach (dynamic friend in myInfo.data)
            {
                // post a test message the friend's wall
                //try
                //{
                //    fb.Post(string.Format("{0}/feed",friend.id), new { message = "My first wall post" });
                //}
                //catch (Exception e)
                //{
                //    string text = e.StackTrace;
                //}



                // does the friend already exist?
                String     strUserId   = result.ProviderUserId;
                Int64      intUserId   = Int64.Parse(strUserId);
                Int64      intfriendId = Int64.Parse(friend.id);
                UserFriend userFriend  = db.UserFriends.FirstOrDefault(u => u.UserFriend_UserFacebookId == intUserId && u.UserFriend_FriendFacebookId == intfriendId);
                if (userFriend == null)
                {
                    UserFriend newUserFriend = new UserFriend();
                    newUserFriend.UserFriend_UserFacebookId   = intUserId;
                    newUserFriend.UserFriend_FriendFacebookId = intfriendId;
                    newUserFriend.UserFriend_Name             = friend.name;

                    // Save the record
                    db.UserFriends.Add(newUserFriend);
                    db.SaveChanges();
                }
            }

            // post a test message on my wall
            //try
            //{
            //    fb.Post("me/feed", new { message = "My second wall post" });
            //}
            //catch (Exception e)
            //{
            //    string text = e.StackTrace;
            //}


            // post a test
            var parameters = new Dictionary <string, object>
            {
                { "event", "http://amovada.azurewebsites.net/Event/Details/1963" },
                { "tags", "585173979" }
            };
            var response = fb.Post("me/amovada:added_you_to", parameters);



            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return(RedirectToLocal(returnUrl));
            }



            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return(RedirectToLocal(returnUrl));
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl           = returnUrl;
                return(View("ExternalLoginConfirmation", new RegisterExternalLoginModel {
                    UserName = result.UserName, ExternalLoginData = loginData
                }));
            }
        }
示例#21
0
 public void CreateOrUpdateAccount(string providerName, string providerUserId, string userName)
 {
     OAuthWebSecurity.CreateOrUpdateAccount(providerName, providerUserId, userName);
 }
示例#22
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                //using (UsersContext db = new UsersContext())
                //{
                //    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                //    // Check if user already exists
                //    if (user == null)
                //    {
                //        // Insert name into the profile table
                //        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                //        db.SaveChanges();

                //        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                //        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                //        return RedirectToLocal(returnUrl);
                //    }
                //    else
                //    {
                //        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                //    }
                //}

                using (SqlConnection pripojeni = new SqlConnection("Data Source=MASTAH-PC;Initial Catalog=PFTDB;Integrated Security=True"))
                {
                    SqlCommand prikaz = new SqlCommand();
                    pripojeni.Open();
                    prikaz.Connection = pripojeni;
                    prikaz.Parameters.AddWithValue("@name", "Beginner");
                    prikaz.CommandText = "SELECT name FROM Difficulty WHERE name = @name";
                    Debug.Write("select sestaven");
                    string email = (string)prikaz.ExecuteScalar();  // metoda vraci typ object - je potreba prevest na int
                    pripojeni.Close();
                    // Check if user already exists
                    if (email == null)
                    {
                        // Insert name into the profile table
                        Debug.Write(email + "DB je prazdna");

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        Debug.Write(email + "DB je naplnena");
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
示例#23
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            //Get result from OpenID provider
            AuthenticationResult authenticationResult = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

            if (!authenticationResult.IsSuccessful)
            {
                return(RedirectToAction("ExternalLoginFailure"));
            }

            //Login with authentication result
            if (OAuthWebSecurity.Login(authenticationResult.Provider, authenticationResult.ProviderUserId, createPersistentCookie: true))
            {
                return(RedirectTo(returnUrl));
            }

            var userName    = OAuthWebSecurity.GetUserName(authenticationResult.Provider, authenticationResult.ProviderUserId);
            var loginData   = OAuthWebSecurity.SerializeProviderUserId(authenticationResult.Provider, authenticationResult.ProviderUserId);
            var displayName = OAuthWebSecurity.GetOAuthClientData(authenticationResult.Provider).DisplayName;

            // If the current user is logged in add the new account
            if (User.Identity.IsAuthenticated)
            {
                OAuthWebSecurity.CreateOrUpdateAccount(authenticationResult.Provider, authenticationResult.ProviderUserId, User.Identity.Name);
                return(RedirectTo(returnUrl));
            }

            var membershipUserIdentifier = Guid.NewGuid().ToString();

            try
            {
                // Insert a new user into the database
                using (var db = dataContextFactory.Create())
                {
                    // Insert name into the profile table
                    db.Users.Add(new User {
                        MembershipUserIdentifier = membershipUserIdentifier, Email = authenticationResult.UserName
                    });
                    db.SaveChanges();
                }
            }
            catch (DbUpdateException e)
            {
                var innerException1 = e.InnerException as System.Data.Entity.Core.UpdateException;
                if (innerException1 == null)
                {
                    throw;
                }

                var innerException2 = innerException1.InnerException as SqlException;
                if (innerException2 == null)
                {
                    throw;
                }

                var innerExceptionMessage = innerException2.Message ?? "";

                if (innerExceptionMessage.Contains("IX_Email") && innerExceptionMessage.Contains("duplicate"))
                {
                    Flash.Error("The email address used to login is already in use on this site using a different login method.  "
                                + "Please login with the original login method used for that email.  "
                                + "Then you may associate other login methods with your account.  ");

                    return(RedirectToAction("Login"));
                }
                else
                {
                    throw;
                }
            }

            OAuthWebSecurity.CreateOrUpdateAccount(authenticationResult.Provider, authenticationResult.ProviderUserId, membershipUserIdentifier);
            OAuthWebSecurity.Login(authenticationResult.Provider, authenticationResult.ProviderUserId, createPersistentCookie: true);

            return(RedirectTo(returnUrl));
        }
示例#24
0
 public bool UpdateOAuthAccount(string username, string provider, string providerUserId)
 {
     OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, username);
     return(true);
 }
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        UserProfile newUser = db.UserProfiles.Add(new UserProfile {
                            UserName = model.UserName
                        });
                        db.SaveChanges();

                        //
                        bool facebookVerified;

                        var     client   = new Facebook.FacebookClient(Session["facebooktoken"].ToString());
                        dynamic response = client.Get("me", new { fields = "verified" });
                        if (response.ContainsKey("verified"))
                        {
                            facebookVerified = response["verified"];
                        }
                        else
                        {
                            facebookVerified = false;
                        }

                        db.ExternalUsers.Add(new ExternalUserInformation
                        {
                            UserId   = newUser.UserId,
                            FullName = model.FullName,
                            Link     = model.Link,
                            Verified = facebookVerified
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
示例#26
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            try
            {
                int tmpUserID = -1;

                AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
                if (!result.IsSuccessful)
                {
                    TempData["Error"] = "Error description: " + result.Error + " " + result.IsSuccessful.ToString();
                    return(RedirectToAction("ExternalLoginFailure"));
                }

                if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
                {
                    //return RedirectToLocal(returnUrl);
                    tmpUserID = WebSecurity.GetUserId(result.UserName);
                }

                if (User.Identity.IsAuthenticated)
                {
                    // If the current user is logged in add the new account
                    OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                    //return RedirectToLocal(returnUrl);
                    tmpUserID = WebSecurity.GetUserId(result.UserName);
                }
                else
                {
                    // User is new, ask for their desired membership name
                    string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                    ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                    ViewBag.ReturnUrl           = returnUrl;
                    //return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });

                    RegisterExternalLoginModel model = new RegisterExternalLoginModel {
                        UserName = result.UserName, Email = result.ExtraData["email"], FullName = result.ExtraData["name"], ExternalLoginData = loginData
                    };
                    string provider       = null;
                    string providerUserId = null;

                    if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
                    {
                        return(RedirectToAction("Manage"));
                    }

                    if (ModelState.IsValid)
                    {
                        //Insert a new user into the database
                        using (UsersContext db = new UsersContext())
                        {
                            UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                            // Check if user already exists
                            if (user == null)
                            {
                                // Insert name into the profile table
                                //GREGA HACKS -- > model.username v providerUserID
                                //db.UserProfiles.Add(new UserProfile { UserName = model.UserName, UserGuid = Guid.NewGuid(), FullName = model.UserName });
                                db.UserProfiles.Add(new UserProfile {
                                    UserName = model.UserName, UserGuid = Guid.NewGuid(), FullName = model.FullName, Email = model.Email
                                });
                                db.SaveChanges();

                                //GREGA HACKS -- > model.username v providerUserID
                                OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName); //???model.Email???
                                                                                                                  //OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, providerUserId);

                                OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                                tmpUserID = WebSecurity.GetUserId(result.UserName);
                            }
                            else
                            {
                                ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                            }
                        }
                    }
                }

                List <FacebookFriend> friendsList  = FacebookDataHelper.GetFriends();
                IUserDataRepository   _repositoryU = new UserDataRepository();
                _repositoryU.AddFBFriends(result.UserName, friendsList);

                if (tmpUserID != -1)
                {
                    Guid id = Guid.Empty;
                    if (RouteData.Values["id"] != null)
                    {
                        Guid.TryParse(RouteData.Values["id"].ToString(), out id);
                    }

                    //UPDATEAMO BET
                    if (id != Guid.Empty)
                    {
                        IBetDataRepository _repositoryB = new BetDataRepository();

                        BetData bet = new BetData();
                        bet.Guid        = id;
                        bet.BetActionID = Convert.ToInt16(RouteData.Values["type"]);

                        if (bet.BetActionID == 115)
                        {
                            bet.User1ID = tmpUserID;
                        }
                        else
                        {
                            bet.User2ID = tmpUserID;
                        }

                        bet.BetStatusID = BetStatus.Accepted;  ///!!!!Request.QueryString["betStatus"].ToEnum<BetStatus>();
                        _repositoryB.Update(bet);

                        //ZAPIŠEMO HISTORY!!!
                        new EventData(bet.Guid, tmpUserID, bet.BetStatusID == BetStatus.Accepted ? 202 : 206).Add();

                        return(RedirectToAction("Index", "Dashboard", new { popup = "typeCredit" + bet.BetID }));
                    }

                    //return RedirectToAction("Index", "Bet");
                    return(RedirectToAction("Support-Me", "Bet"));
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    return(View());
                }
            }
            catch (Exception e)
            {
                Neolab.Common.NeoException.Handle(e);
                return(RedirectToAction("Index", "Error"));
            }
        }
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

            if (!result.IsSuccessful)
            {
                return(RedirectToAction("ExternalLoginFailure"));
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return(RedirectToLocal(returnUrl));
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                if (result.Provider == "facebook" || result.Provider == "google")
                {
                    using (UsersContext db = new UsersContext())
                    {
                        UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == User.Identity.Name);
                        if (user != null)
                        {
                            var oauthItem = db.OAuthMemberships.FirstOrDefault(x => x.Provider == result.Provider && x.ProviderUserId == result.ProviderUserId && x.UserId == user.UserId);
                            if (oauthItem != null)
                            {
                                oauthItem.Email = result.UserName;
                                db.SaveChanges();
                            }
                        }
                    }
                }
                return(RedirectToLocal(returnUrl));
            }
            else
            {
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl           = returnUrl;
                var model = new RegisterExternalLoginModel {
                    UserName = result.UserName, ExternalLoginData = loginData
                };
                switch (result.Provider)
                {
                case "facebook":
                case "google":
                {
                    model.Email    = result.UserName;
                    model.UserName = "";
                    break;
                }

                case "twitter":
                {
                    model.Email    = "";
                    model.UserName = result.UserName;
                    break;
                }

                default:
                    break;
                }
                return(View("ExternalLoginConfirmation", model));
            }
        }
示例#28
0
        public virtual ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

            if (!result.IsSuccessful)
            {
                return(RedirectToAction("ExternalLoginFailure"));
            }

            if (result.ExtraData.Keys.Contains("accesstoken"))
            {
                Session["googletoken"] = result.ExtraData["accesstoken"];
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return(RedirectToLocal(returnUrl));
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return(RedirectToLocal(returnUrl));
            }
            else
            {
                // User is new, ask for their desired membership name
                //string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                //ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                //ViewBag.ReturnUrl = returnUrl;
                //return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });

                var username = result.UserName;

                // Insert a new user into the database
                using (VroemmmContext db = new VroemmmContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == username);
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile {
                            UserName = username
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, username);
                        OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "Je hebt al een acccount");
                    }
                }

                return(RedirectToLocal(returnUrl));
            }
        }
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(returnUrl);

            if (!result.IsSuccessful)
            {
                return(this.RedirectToAction("ExternalLoginFailure"));
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                UserProfile userProfile = this.userManager.GetUserProfileFromProvider(result.Provider, result.ProviderUserId);
                IEnumerable <AccessDetails> accessDetails = this.userManager.GetUserAccessDetails(userProfile.RowKey);
                var isRegionAdmin = accessDetails.Any(x => x.AccessLevel == AccessLevels.Admin);

                this.CreateAuthenticationTicket(result.ExtraData["name"].ToString(), result.ExtraData["accesstoken"].ToString(), DateTime.Now, userProfile.IsSuperAdmin, isRegionAdmin);

                this.RegisterLogger.Log(TraceEventType.Information, LoggingMessageId.PortalUserLoggedIn, userProfile.UserName + " has logged in to the portal");

                return(this.RedirectToLocal(returnUrl));
                //// return this.Redirect(redirectUrl);
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                UserProfile userProfile = this.userManager.GetUserProfileFromProvider(result.Provider, result.ProviderUserId);
                IEnumerable <AccessDetails> accessDetails = this.userManager.GetUserAccessDetails(userProfile.RowKey);
                var isRegionAdmin = accessDetails.Any(x => x.AccessLevel == AccessLevels.Admin);

                this.CreateAuthenticationTicket(User.Identity.Name, result.ExtraData["accesstoken"].ToString(), DateTime.Now, userProfile.IsSuperAdmin, isRegionAdmin);

                return(this.RedirectToLocal(returnUrl));
            }
            else
            {
                // User is new, ask for them to register
                string accessToken = result.ExtraData["accesstoken"].ToString();
                var    userData    = this.userManager.GetClientUserDataByAccessToken(accessToken);
                userData.AccessToken = accessToken;

                this.TempData["ClientUserData"] = userData;

                RegisterExternalLoginModel registerModel = new RegisterExternalLoginModel
                {
                    FirstName         = userData.FirstName,
                    LastName          = userData.LastName,
                    UserName          = string.IsNullOrEmpty(userData.UserName) ? userData.Emails.Account : userData.UserName,
                    AccountEmail      = userData.Emails.Account,
                    PreferredEmail    = userData.Emails.Preferred,
                    City              = userData.Business != null ? userData.Business.City : string.Empty,
                    ExternalLoginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId),
                };

                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl           = returnUrl;
                ViewBag.Country             = new SelectList(Utility.GetCounties());
                ViewBag.TimeZone            = new SelectList(Utility.GetTimeZones(), "(UTC-08:00) Pacific Time (US & Canada)");
                ViewBag.PhoneCountryCode    = new SelectList(Utility.GetCountryPhoneCodes(), "United States(+1)");
                return(this.View("Register", registerModel));
            }
        }
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(this.RedirectToAction("Index", "Home"));
            }

            if (ModelState.IsValid)
            {
                UserProfile userProfile = this.userManager.GetUserProfileFromProvider(provider, providerUserId);

                if (userProfile == null)
                {
                    ClientUserData clientUserData = (ClientUserData)TempData["ClientUserData"];

                    Random random = new Random();
                    int    userId = random.Next(int.MaxValue);

                    userProfile = new UserProfile
                    {
                        RowKey           = userId.ToString(),
                        UserName         = string.IsNullOrEmpty(clientUserData.UserName) ? clientUserData.Emails.Account : clientUserData.UserName,
                        AccountEmail     = clientUserData.Emails.Account,
                        FirstName        = model.FirstName,
                        LastName         = model.LastName,
                        City             = model.City,
                        Country          = model.Country,
                        State            = model.State,
                        PreferredEmail   = model.PreferredEmail,
                        Gender           = clientUserData.Gender,
                        Link             = Convert.ToString(clientUserData.Link),
                        IsSuperAdmin     = false,
                        TimeZone         = model.TimeZone,
                        CreatedTime      = DateTime.Now.ToUniversalTime().ToString(),
                        Address1         = model.Address1,
                        Address2         = model.Address2,
                        Phone            = model.Phone,
                        PhoneCountryCode = model.PhoneCountryCode,
                        ZipCode          = model.ZipCode
                    };

                    var regions = this.regionSource.GetAvailableRegions();
                    List <AccessDetails> defaultAccess = new List <AccessDetails>();

                    foreach (var region in regions)
                    {
                        var accessDetail = new AccessDetails
                        {
                            AccessLevel = AccessLevels.PortalUser,
                            Authority   = (Authorities)Convert.ToInt32(region.RegionInformation.Id)
                        };

                        defaultAccess.Add(accessDetail);
                    }

                    this.userManager.SaveUserDetails(
                        new UserDetails
                    {
                        UserInfo   = userProfile,
                        AccessInfo = defaultAccess,
                    });

                    this.RegisterAuditor.TransactionId = this.RegisterLogger.TransactionId;
                    this.RegisterAuditor.Audit(AuditId.RegisterUser, AuditStatus.Success, default(int), userProfile.UserName + " Registered Successfully");
                    this.RegisterLogger.Log(TraceEventType.Information, LoggingMessageId.PortalUserRegistration, userProfile.UserName + " registered to the portal");

                    OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                    OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
                    this.RegisterLogger.Log(TraceEventType.Information, LoggingMessageId.PortalUserLoggedIn, userProfile.UserName + " has logged in to the portal");

                    // By Default IsSuperAdmin is false
                    this.CreateAuthenticationTicket(model.UserName, clientUserData.AccessToken, DateTime.Now, false, false);
                    return(this.RedirectToLocal(returnUrl));
                }
                else
                {
                    ModelState.AddModelError("UserName", "User already exists. Please enter a different user name.");
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            ViewBag.Country             = new SelectList(Utility.GetCounties());
            ViewBag.TimeZone            = new SelectList(Utility.GetTimeZones());
            ViewBag.PhoneCountryCode    = new SelectList(Utility.GetCountryPhoneCodes());
            return(this.View("Register", model));
        }