示例#1
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            if (Request.IsAuthenticated)
            {
                return(RedirectToManageLoginsPage(UnexpectedExtrnalLoginError));
            }

            var loginInfo = await OwinAuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login", new { error = "external-login-failure" }));
            }

            var user = await OwinUserManager.FindAsync(loginInfo.Login);

            if (user != null)
            {
                // The user has an acoount. Sign her in.
                await new LoginHelper(OwinUserManager, OwinAuthenticationManager).Sigin(user, true);
                return(RedirectToLocal(returnUrl));
            }
            else
            {
                // If the user does not have an account, then prompt the user to create an account.
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                ViewBag.ReturnUrl     = returnUrl;
                var model = new ExternalLoginBindingModel
                {
                    Email = loginInfo.Email,
                    Name  = loginInfo.ExternalIdentity.Name
                };
                return(View("ExternalLoginConfirmation", model));
            }
        }
        public async Task <IHttpActionResult> PostForgot(JObject value)
        {
            var email = (string)value["email"];

            if (!String.IsNullOrEmpty(email))
            {
                var user = await OwinUserManager.FindByEmailAsync(email.Trim());

                if (user != null)
                {
                    if (await OwinUserManager.IsEmailConfirmedAsync(user.Id))
                    {
                        // Send the link.
                        var token = await OwinUserManager.GeneratePasswordResetTokenAsync(user.Id);

                        var queryString = AccountUtils.GetMailLinkQueryString(token, user.Id);
                        var host        = Request.RequestUri.GetComponents(UriComponents.Host, UriFormat.Unescaped);
                        var link        = "https://" + host + "/account/reset-password?" + queryString;
                        await EmailUtils.SendPasswordResetEmailAsync(email, link);
                    }
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public async Task <IHttpActionResult> PostLogin(JObject value)
        {
            var userName   = (string)value["userName"];
            var password   = (string)value["password"];
            var persistent = (bool)value["persistent"];

            ApplicationUser user = await OwinUserManager.FindAsync(userName, password);

            if (user == null)
            {
                return(BadRequest("The email address or password is incorrect."));
            }

            await new LoginHelper(OwinUserManager, OwinAuthenticationManager).Sigin(user, persistent);

            return(StatusCode(HttpStatusCode.NoContent));

            /*
             * Just in case. In the opposite case of token/bearer authentication. How to pass custom values to the OWIN middleware.
             * data: {
             *  grant_type: 'password',
             *  userName: userName,
             *  password: password,
             *  scope: persistent ? 'persistent_cookie' : 'session_cookie', // Pass our custom value. Scope may be a list of values separated by spaces.
             * },
             * public override void GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
             * {
             *  // AF. A hack to enable the option of session or persistent cookies. We piggy-back the request and pass our custom value. Scope may be sent as a list of values separated by spaces.
             *  var isPersistent = context.Scope.Any(i => i == "persistent_cookie");
             * }
             */
        }
        public async Task <IHttpActionResult> GetLogins()
        {
            var userId = this.GetUserId();

            var userLogins = (await OwinUserManager.GetLoginsAsync(userId))
                             .Select(i => new
            {
                LoginProvider = i.LoginProvider,
                ProviderKey   = i.ProviderKey,
            })
                             .ToList();

            var otherLogins = OwinAuthenticationManager.GetExternalAuthenticationTypes()
                              .Where(i => userLogins.All(u => u.LoginProvider != i.AuthenticationType))
                              .Select(i => i.AuthenticationType)
                              .ToList();


            var hasPassword = await OwinUserManager.HasPasswordAsync(userId);

            //var user = OwinUserManager.FindById(this.GetUserId());
            //var hasPassword = (user != null) && !String.IsNullOrEmpty(user.PasswordHash);

            var result = new
            {
                UserLogins  = userLogins,
                OtherLogins = otherLogins,
                HasPassword = hasPassword,
            };

            return(Ok(result));
        }
示例#5
0
        public async Task <ActionResult> LinkLoginCallback()
        {
            var loginInfo = await OwinAuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, this.GetUserId().ToString());

            string error = loginInfo != null ? null : "External login failed";

            if (error == null)
            {
                var result = await OwinUserManager.AddLoginAsync(this.GetUserId(), loginInfo.Login);

                error = result.PlainErrorMessage("Failed to link external login");
            }
            return(new RedirectResult(Url.Action("Edit", "Account", null, "https") + "#/logins" + (error == null ? "" : "?error=" + Uri.EscapeUriString(error)))); // Uri.Encode replaces spaces with '+', not '%20'
        }
        public async Task <IHttpActionResult> PostReset([FromUri] string code, [FromUri] string time, [FromBody] JObject value)
        {
            //string code = IdentityHelper.GetCodeFromRequest(Request);
            int userId = AccountUtils.GetUserIdFromQueryStringValue(time);

            if (String.IsNullOrEmpty(code) || userId == 0)
            {
                return(BadRequest());
            }
            var password = (string)value["password"];
            var result   = await OwinUserManager.ResetPasswordAsync(userId, code, password);

            return(result.Succeeded
                ? StatusCode(HttpStatusCode.NoContent)
                : (IHttpActionResult)BadRequest(result.PlainErrorMessage()));
        }
        public async Task <IHttpActionResult> PostPhoneVerification(JObject value)
        {
            var phoneNumber = (string)value["phoneNumber"];
            var code        = (string)value["phoneCode"];

            if (String.IsNullOrWhiteSpace(phoneNumber) || String.IsNullOrWhiteSpace(code))
            {
                return(BadRequest());
            }
            phoneNumber = phoneNumber.Trim();

            var result = await OwinUserManager.ChangePhoneNumberAsync(this.GetUserId(), phoneNumber, code);

            return(result.Succeeded
                ? (IHttpActionResult)StatusCode(HttpStatusCode.NoContent)
                : (IHttpActionResult)BadRequest("Failed to verify phone"));
        }
        public async Task <IHttpActionResult> DeleteExternalLogin([FromUri] string loginProvider, [FromUri] string providerKey)
        {
            var result = await OwinUserManager.RemoveLoginAsync(this.GetUserId(), new UserLoginInfo(loginProvider, providerKey));

            if (result.Succeeded)
            {
                var user = await OwinUserManager.FindByIdAsync(this.GetUserId());

                if (user != null)
                {
                    await new LoginHelper(OwinUserManager, OwinAuthenticationManager).Sigin(user, false);
                }
            }
            else
            {
                throw new Exception(result.PlainErrorMessage("Failed to remove external login"));
            }
            return(StatusCode(HttpStatusCode.NoContent));
        }
        public async Task <IHttpActionResult> PutPassword(JObject value)
        {
            var oldPassword = (string)value["oldPassword"];
            var newPassword = (string)value["newPassword"];
            var userId      = this.GetUserId();

            var result = String.IsNullOrEmpty(oldPassword)
                ? await OwinUserManager.AddPasswordAsync(userId, newPassword)
                : await OwinUserManager.ChangePasswordAsync(userId, oldPassword, newPassword);

            if (result.Succeeded)
            {
                OwinAuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                return(StatusCode(HttpStatusCode.NoContent));
            }
            else
            {
                return(BadRequest(result.PlainErrorMessage()));
            }
        }
示例#10
0
        public async Task <IHttpActionResult> PostPhoneNumber(JObject value)
        {
            var    phoneNumber = (string)value["phoneNumber"];
            string code        = null;

            if (!String.IsNullOrEmpty(phoneNumber))
            {
                code = await OwinUserManager.GenerateChangePhoneNumberTokenAsync(this.GetUserId(), phoneNumber.Trim());
            }
            if (!String.IsNullOrEmpty(code))
            {
                return(StatusCode(HttpStatusCode.NoContent));
                // Do not return the code to the client while in production! Send it via SMS.
                //return Ok(code);
            }
            else
            {
                return(BadRequest("Verification code not sent."));
            }

            // A phone number can be removed by calling UserManager.SetPhoneNumberAsync(userId, null);
        }
示例#11
0
        public async Task <ActionResult> ConfirmEmail()
        {
            int    userId  = AccountUtils.GetUserIdFromRequest(Request);
            string code    = AccountUtils.GetCodeFromRequest(Request);
            bool   success = false;

            if (userId != 0 && !String.IsNullOrEmpty(code))
            {
                var result = await OwinUserManager.ConfirmEmailAsync(userId, code);

                success = result.Succeeded;
            }
            if (success && Request.IsAuthenticated)
            {
                return(Redirect(Url.Action("Edit", "Account", null, "https") + "#/logins"));
            }
            else
            {
                // If the user comes to the Login page authenticated, she gets redirected further to the login management page.
                OwinAuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                return(Redirect(Url.Action("Login", "Account", new { confirmed = success }, "https")));
            }
        }
示例#12
0
        public async Task <IHttpActionResult> PutEmail(JObject value)
        {
            var userId = this.GetUserId();

            // TODO. Store the old confirmed email. To replace a confirmed email with an unconfirmed one is a bed idea. But we have no infrastructure currently to store an unconfirmed email temporarily.
            if (await OwinUserManager.IsEmailConfirmedAsync(userId))
            {
                return(BadRequest("Unable to change a confirmed email address."));
            }

            var email = (string)value["email"];

            if (String.IsNullOrWhiteSpace(email))
            {
                return(BadRequest());
            }
            email = email.Trim();

            var result = await OwinUserManager.SetEmailAsync(userId, email);

            if (result.Succeeded)
            {
                var confirmationToken = await OwinUserManager.GenerateEmailConfirmationTokenAsync(userId);

                var queryString = AccountUtils.GetMailLinkQueryString(confirmationToken, userId);
                var host        = Request.RequestUri.GetComponents(UriComponents.Host, UriFormat.Unescaped);
                var link        = "http://" + host + "/account/confirm-email?" + queryString;
                var displayName = this.GetUserDisplayName();
                await EmailUtils.SendVerificationEmailAsync(email, displayName, link);

                return(StatusCode(HttpStatusCode.NoContent));
            }
            else
            {
                return(BadRequest(result.PlainErrorMessage("Failed to change email address.")));
            }
        }