Esempio n. 1
0
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string          ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId?message      = null;

            // Only disassociate the account if the currently logged in user is the owner
            if (ownerAccount == User.Identity.Name)
            {
                // Use a transaction to prevent the user from deleting their last login credential
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {
                    IsolationLevel = IsolationLevel.Serializable
                }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return(RedirectToAction("Manage", new { Message = message }));
        }
Esempio n. 2
0
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string          ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId?message      = null;

            // Удалять связь учетной записи, только если текущий пользователь — ее владелец
            if (ownerAccount == User.Identity.Name)
            {
                // Транзакция используется, чтобы помешать пользователю удалить учетные данные последнего входа
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {
                    IsolationLevel = IsolationLevel.Serializable
                }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return(RedirectToAction("Manage", new { Message = message }));
        }
Esempio n. 3
0
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string          ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId?message      = null;

            // Desasociar la cuenta solo si el usuario que ha iniciado sesión es el propietario
            if (ownerAccount == User.Identity.Name)
            {
                // Usar una transacción para evitar que el usuario elimine su última credencial de inicio de sesión
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {
                    IsolationLevel = IsolationLevel.Serializable
                }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return(RedirectToAction("Manage", new { Message = message }));
        }
Esempio n. 4
0
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string          ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId?message      = null;

            // 只有在当前登录用户是所有者时才取消关联帐户
            if (ownerAccount == User.Identity.Name)
            {
                // 使用事务来防止用户删除其上次使用的登录凭据
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {
                    IsolationLevel = IsolationLevel.Serializable
                }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return(RedirectToAction("Manage", new { Message = message }));
        }
Esempio n. 5
0
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string          ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId?message      = null;

            // Dissocier uniquement le compte si l'utilisateur actuellement connecté est le propriétaire
            if (ownerAccount == User.Identity.Name)
            {
                // Utiliser une transaction pour empêcher l'utilisateur de supprimer ses dernières informations d'identification de connexion
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {
                    IsolationLevel = IsolationLevel.Serializable
                }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return(RedirectToAction("Manage", new { Message = message }));
        }
Esempio n. 6
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            var url = Url.Action("ExternalLoginCallback");



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



            FacebookToken = result.ExtraData["accesstoken"];
            Provider      = result.Provider;
            if (Provider == "facebook")
            {
                string token = FacebookAPI.GetLongtermFbToken(FacebookToken);
                FacebookToken = token;
            }

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

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                string            username  = OAuthWebSecurity.GetUserName(result.Provider, result.ProviderUserId);
                int               userId    = WebSecurity.GetUserId(username);
                FacebookScheduler scheduler = new FacebookScheduler();
                scheduler.RunScheduler(FacebookToken, userId);

                return(RedirectToLocal(returnUrl));
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                DatabaseCallsApi _api = new DatabaseCallsApi();

                var username = OAuthWebSecurity.GetUserName(result.Provider, result.ProviderUserId);
                int user_id  = WebSecurity.GetUserId(username);
                _api.AddOrUpdateService(user_id, result.Provider, FacebookToken);
                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
                }));
            }
        }
Esempio n. 7
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(base.Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

            if (!result.IsSuccessful)
            {
                return(base.RedirectToAction("ExternalLoginFailure"));
            }
            bool   flag     = false;
            string userName = OAuthWebSecurity.GetUserName(result.Provider, result.ProviderUserId);

            if (userName != null)
            {
                flag = WebSecurity.IsConfirmed(userName);
                if (flag)
                {
                    bool createPersistentCookie = false;
                    if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie))
                    {
                        return(this.RedirectToLocal(returnUrl));
                    }
                    if (base.User.Identity.IsAuthenticated)
                    {
                        OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, base.User.Identity.Name);
                        return(this.RedirectToLocal(returnUrl));
                    }
                }
                else
                {
                    string userConfirmationToken = MembershipHelper.GetUserConfirmationToken(WebSecurity.GetUserId(userName));
                    if (userConfirmationToken != null)
                    {
                        this.SendRegistrationConfirmMail(ConfirmMailOperation.confirm, userName, userConfirmationToken);
                    }
                }
            }
            ((dynamic)base.ViewBag).NotConfirmedEmail = (userName != null) && !flag;
            string str3 = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
            AuthenticationClientData oAuthClientData = OAuthWebSecurity.GetOAuthClientData(result.Provider);

            ((dynamic)base.ViewBag).ProviderDisplayName = oAuthClientData.DisplayName;
            ((dynamic)base.ViewBag).ReturnUrl           = returnUrl;
            RegisterExternalLoginModel model = new RegisterExternalLoginModel {
                UserName          = (result.UserName.Contains("@") && result.UserName.Contains(".")) ? result.UserName : "",
                ExternalLoginData = str3
            };

            return(base.View("ExternalLoginConfirmation", model));
        }
        public IHttpActionResult ExternalLoginFinal(string provider, string providerUserId)
        {
            IHttpActionResult result;

            if (OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false))
            {
                var username = OAuthWebSecurity.GetUserName(provider, providerUserId);
                result = Ok(username);
            }
            else
            {
                result = BadRequest();
            }

            return(result);
        }
Esempio n. 9
0
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string          ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId?message      = null;

            // 只有在当前登录用户是所有者时才取消关联帐户
            if (ownerAccount == User.Identity.Name)
            {
                // 使用事务来防止用户删除其上次使用的登录凭据
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {
                    IsolationLevel = IsolationLevel.Serializable
                }))
                {
                }
            }

            return(RedirectToAction("Manage", new { Message = message }));
        }
Esempio n. 10
0
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string          ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId?message      = null;

            if (ownerAccount == User.Identity.Name)
            {
                using (DataContext db = new DataContext())
                {
                    ExternalLoginProfile externalProfile = db.ExternalLoginProfiles.Include("User").FirstOrDefault(e => e.User.UserName.Equals(User.Identity.Name, StringComparison.OrdinalIgnoreCase));
                    if (externalProfile != null)
                    {
                        db.ExternalLoginProfiles.Remove(externalProfile);
                        db.SaveChanges();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return(RedirectToAction("Manage", new { Message = message }));
        }
Esempio n. 11
0
        public OAuthResult GetOAuthResult(string encryptedLoginData)
        {
            string provider       = null;
            string providerUserId = null;
            var    oAuth          = new OAuthResult();

            if (!TryDecryptProviderData(encryptedLoginData, out provider, out providerUserId))
            {
                return(oAuth);
            }


            oAuth.IsValid             = true;
            oAuth.Provider            = provider;
            oAuth.ProviderUserId      = providerUserId;
            oAuth.UserName            = OAuthWebSecurity.GetUserName(provider, providerUserId);
            oAuth.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            oAuth.EncryptedLoginData  = encryptedLoginData;

            return(oAuth);
        }
        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));
            }
        }
Esempio n. 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));
            }
        }
Esempio n. 14
0
        public HttpResponseMessage Disassociate(DissasociateModel model)
        {
            string ownerAccount = OAuthWebSecurity.GetUserName(model.Provider, model.ProviderUserId);

            // Disassociate account if authenticated user is the owner
            if (ownerAccount == User.Identity.Name)
            {
                // Using transaction to avoid dissasociation of the last linked account
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {
                    IsolationLevel = IsolationLevel.Serializable
                }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(model.Provider, model.ProviderUserId);
                        scope.Complete();
                    }
                }
                return(Request.CreateResponse(HttpStatusCode.OK, "Account succesfully dissasociated"));
            }

            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "You are not the account owner"));
        }
Esempio n. 15
0
        public bool Disassociate(string provider, string providerUserId)
        {
            bool   success      = false;
            string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);

            // Only disassociate the account if the currently logged in user is the owner
            if (ownerAccount == CurrentUser.Identity.Name)
            {
                // Use a transaction to prevent the user from deleting their last login credential
                using (var scope = new System.Transactions.TransactionScope(TransactionScopeOption.Required, new TransactionOptions {
                    IsolationLevel = IsolationLevel.Serializable
                }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(CurrentUser.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(CurrentUser.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        success = true;
                    }
                }
            }
            return(success);
        }
Esempio n. 16
0
        public IEnumerable <ViewCommentHistory> Get([FromUri] int Id)
        {
            List <Comment>            list   = _db.Comment.Select(c => c).Where(c => c.ProposalId == Id).ToList();
            List <ViewCommentHistory> output = new List <ViewCommentHistory>();

            foreach (var item in list)
            {
                Models.User user = _db.User.FirstOrDefault(c => c.UserId == item.CreatedBy);
                if (item.CreatedBy == WebSecurity.CurrentUserId)//check if owner of the comment
                {
                    output.Add(new ViewCommentHistory {
                        Id = item.Id.ToString(), Body = item.Body, CreatedBy = user.Name, DateCreated = item.CreatedDate.ToString(@"yyyy-MM-ddTHH\:mm\:ss.fffffffzzz"), UserId = user.Id.ToString(), isFacebook = false
                    });
                }
                else
                {
                    output.Add(new ViewCommentHistory {
                        Body = item.Body, CreatedBy = user.Name, DateCreated = item.CreatedDate.ToString(@"yyyy-MM-ddTHH\:mm\:ss.fffffffzzz"), UserId = user.UserId.ToString(), isFacebook = false
                    });
                }
            }
            //get a service facebook or twitter
            Service service = _db.User.FirstOrDefault(c => c.UserId == WebSecurity.CurrentUserId).Services.FirstOrDefault(c => c.Provider == "facebook");

            if (service != null)
            {
                FacebookAPI facebook = new FacebookAPI(service.Token);
                Proposal    proposal = _db.Proposal.FirstOrDefault(c => c.Id == Id && c.FacebookPostId != null && c.FacebookPostId != "");

                if (proposal != null)
                {
                    dynamic comments = facebook.getComments(proposal.FacebookPostId);     //get facebook post comments
                    if ((comments is int) == false && comments != null && comments.ContainsKey("data"))
                    {
                        foreach (dynamic item in comments.data)
                        {
                            string id                    = item.id;
                            string body                  = item.message;
                            string created_date          = item.created_time;
                            string created_by            = item.from.name;
                            string created_by_facebookID = item.from.id;
                            string userID                = OAuthWebSecurity.GetUserName("facebook", created_by_facebookID);
                            var    LoggedInUserID        = OAuthWebSecurity.GetAccountsFromUserName(userID).FirstOrDefault(c => c.Provider == "facebook").ProviderUserId;


                            if (LoggedInUserID != null && LoggedInUserID == created_by_facebookID)
                            {
                                output.Add(new ViewCommentHistory {
                                    Id = id, Body = body, DateCreated = created_date, CreatedBy = created_by, UserId = created_by_facebookID, isFacebook = true, Artist = false
                                });
                            }
                            else
                            {
                                output.Add(new ViewCommentHistory {
                                    Body = body, DateCreated = created_date, CreatedBy = created_by, UserId = created_by_facebookID, isFacebook = true, Artist = false
                                });
                            }
                        }
                    }
                    output = output.OrderByDescending(c => DateTime.Parse(c.DateCreated)).ToList();     //reorder the comments
                    if (proposal.FacebookPostIdArtist != "" && proposal.FacebookPostIdArtist != null)   //used to identify if an artist post has been made if yes then grab the latest comment from Artist
                    {
                        comments = facebook.getComments(proposal.FacebookPostIdArtist);
                        if ((comments is int) == false && comments != null && comments.ContainsKey("data"))
                        {
                            foreach (dynamic item in comments.data)
                            {
                                string id                    = item.id;
                                string body                  = item.message;
                                string created_date          = item.created_time;
                                string created_by            = item.from.name;
                                string created_by_facebookID = item.from.id;

                                output.Insert(0, new ViewCommentHistory {
                                    Body = body, DateCreated = created_date, CreatedBy = created_by, UserId = created_by_facebookID, isFacebook = true, Artist = true
                                });
                                break;
                            }
                        }
                    }
                }
                proposal = _db.Proposal.FirstOrDefault(c => c.Id == Id && c.FacebookPostId != null && c.FacebookPostId != "");
            }


            output = output.OrderByDescending(c => DateTime.Parse(c.DateCreated)).ToList();
            return(output.ToList());
        }
Esempio n. 17
0
 public string GetUserName(string providerName, string providerUserId)
 {
     return(OAuthWebSecurity.GetUserName(providerName, providerUserId));
 }
Esempio n. 18
0
        public ActionResult FBAuth(string returnUrl)
        {
            var client      = new FacebookClient();
            var oauthResult = client.ParseOAuthCallbackUrl(Request.Url);

            // Build the Return URI form the Request Url
            var redirectUri = new UriBuilder(Request.Url);

            redirectUri.Path = Url.Action("FbAuth", "Account");
            dynamic result = client.Get("/oauth/access_token", new //get the facebook token
            {
                client_id     = Settings.Settings.FacebookAppId,
                redirect_uri  = Settings.Settings.FacebookCallbackURL,
                client_secret = Settings.Settings.FacebookAppSecret,
                code          = oauthResult.Code,
            });


            if (result == null)
            {
                return(RedirectToAction("ExternalLoginFailure"));
            }
            string accessToken = result.access_token;
            string token       = FacebookAPI.GetLongtermFbToken(accessToken); //get a 2month token

            FacebookToken = accessToken;
            Provider      = "facebook";
            dynamic me = client.Get("/me", //get some basic user info
                                    new
            {
                fields       = "first_name,last_name,email",
                access_token = accessToken
            });

            if (OAuthWebSecurity.Login("facebook", me.id, createPersistentCookie: false))
            {
                string            username  = OAuthWebSecurity.GetUserName("facebook", me.id);
                int               userId    = WebSecurity.GetUserId(username);
                FacebookScheduler scheduler = new FacebookScheduler(); //run any undone task
                scheduler.RunScheduler(token, userId);

                return(RedirectToLocal(returnUrl));
            }
            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                DatabaseCallsApi _api = new DatabaseCallsApi();

                var username = OAuthWebSecurity.GetUserName("facebook", me.id);


                _api.AddOrUpdateService(WebSecurity.CurrentUserId, "facebook", token);
                OAuthWebSecurity.CreateOrUpdateAccount("facebook", me.id, WebSecurity.CurrentUserName.ToString());

                return(RedirectToLocal(returnUrl));
            }
            else
            {
                // User is new, ask for their desired membership name

                CheckChanceState();

                string loginData = OAuthWebSecurity.SerializeProviderUserId("facebook", me.id);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData("facebook").DisplayName;
                ViewBag.ReturnUrl           = returnUrl;
                return(View("ExternalLoginConfirmation", new RegisterExternalLoginModel {
                    UserName = me.email, ExternalLoginData = loginData, Email = me.email
                }));
            }
        }
        public async Task <HttpResponseMessage> Login([FromBody] string assertion)
        {
            if (assertion == null)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            using (var client = new HttpClient())
            {
                var content = new FormUrlEncodedContent(
                    new Dictionary <string, string> {
                    { "assertion", assertion },
                    { "audience", Request.RequestUri.Host },
                }
                    );
                var result = await client.PostAsync("https://verifier.login.persona.org/verify", content);

                result.EnsureSuccessStatusCode();
                var stringresult = await result.Content.ReadAsStringAsync();

                dynamic jsonresult = JsonConvert.DeserializeObject <dynamic>(stringresult);
                if (jsonresult.status == "okay")
                {
                    string email = jsonresult.email;

                    string userName = null;
                    if (User.Identity.IsAuthenticated)
                    {
                        userName = User.Identity.Name;
                    }
                    else
                    {
                        userName = OAuthWebSecurity.GetUserName("Persona", email);
                        if (userName == null)
                        {
                            userName = email; // TODO: prompt for user name
                            using (UsersContext db = new UsersContext())
                            {
                                UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == userName.ToLower());
                                // 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("Persona", email, userName);


                    FormsAuthentication.SetAuthCookie(email, false);
                    return(new HttpResponseMessage(HttpStatusCode.OK));
                }
            }
            return(new HttpResponseMessage(HttpStatusCode.Forbidden));
        }
Esempio n. 20
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));
        }