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));
        }
Beispiel #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));
        }
Beispiel #3
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

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

            if (ModelState.IsValid)
            {
                // Добавление нового пользователя в базу данных
                using (MuseumContext db = new MuseumContext())
                {
                    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));
        }
Beispiel #5
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)
            {
                // 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));
        }
        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));
        }
Beispiel #7
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));
        }
        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 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));
            }
        }
Beispiel #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));
            }
        }
Beispiel #11
0
        //
        // GET: /Account/ExternalLoginCallback

        public ActionResult ExternalLoginCallback(string returnUrl) // Oauth/callback
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

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

            // existing account

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                SetCustomAuthenticationCookie(email: result.ExtraData["email"], rememberMe: false);

                return(RedirectToLocal(returnUrl));
            }

            // create new account with default values set (notice the 'true' argument).
            // ** Prototype patterns

            var user = new User(true)
            {
                FirstName = result.ExtraData["first_name"],
                LastName  = result.ExtraData["last_name"],
                Email     = result.ExtraData["email"],
                City      = result.ExtraData["city"],
                Country   = result.ExtraData["country"]
            };

            // ** Facade pattern. Unit of Work pattern.

            Service.InsertOAuthUser(user, result.Provider, result.ProviderUserId, "Member");

            OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false);
            SetCustomAuthenticationCookie(user.Email, rememberMe: false);

            return(RedirectToLocal(returnUrl));
        }
        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));
        }
Beispiel #13
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));
        }
        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
                }));
            }
        }
Beispiel #15
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 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));
        }
Beispiel #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 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));
        }
Beispiel #18
0
        public ActionResult ForceWixUserSignIn(string email, string returnUrl, string trackingId = null)
        {
            string error = null;
            bool   loginResult;

            var qs_params = ParseReturnUrlQS(returnUrl);

            //check if external login
            var externalLogin = OAuthWebSecurity.GetAccountsFromUserName(email).FirstOrDefault();

            if (externalLogin != null)
            {
                var result = externalLogin;
                loginResult = OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, IS_PERSISTENT_COOKIE) && CreateAuthenticationTicket(email, string.Empty, trackingId, out error);
            }
            else
            {
                loginResult = CreateAuthenticationTicket(email, string.Empty, trackingId, out error);
            }

            //ALWAYS return true  , otherwise it could create endless loop on trying to login
            return(RedirectToAction("WixLoginResultHandler", "Account", new { area = "WixEndPoint", success = true, qs_params.instanceToken, qs_params.uid, qs_params.instanceId, origCompIdToken = qs_params.origCompId, compIdToken = qs_params.compId, error = error + (loginResult ? "" : "something went wrong") }));
        }
Beispiel #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 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));
        }
Beispiel #20
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));
            }
        }
        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));
        }
Beispiel #22
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            string code       = Request.QueryString["code"];
            string returnUrl1 = Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl });

            IDictionary <string, string> userData = new Facebook().GetUserData(code, HttpUtility.HtmlEncode(Url.Action("ExternalLoginCallback", "Account", null, Request.Url.Scheme, null)));
            //IDictionary<string, string> userData2 = new Facebook().GetUserData(code, HttpUtility.HtmlEncode("h" + System.Web.HttpContext.Current.Request.Url.ToString().Substring("h", "/Account") + returnUrl1));

            AuthenticationResult result;

            // User selected yes on permissions, use custom login
            if (userData != null)
            {
                result = new AuthenticationResult(isSuccessful: true, provider: "facebook", providerUserId: userData["id"], userName: userData["username"], extraData: userData);
            }
            else // User selected no on permissions, use default login
            {
                result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            }

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

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

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

            // Store FBID in session
            Session["FBID"]      = result.ProviderUserId;
            Session["LogInTime"] = DateTime.Now;

            return(RedirectToLocal(returnUrl));
        }
        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));
        }
Beispiel #24
0
 public bool Login(string providerName, string providerUserId, bool createPersistentCookie)
 {
     return(OAuthWebSecurity.Login(providerName, providerUserId, createPersistentCookie));
 }
        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));
            }
        }
Beispiel #26
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(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
                }));
            }
        }
        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(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));
        }
Beispiel #30
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"));
            }
        }