Exemplo n.º 1
0
        /// <summary>
        ///     <inheritdoc />
        /// </summary>
        /// <param name="model"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task <User> LoginAsync(LoginViewModel model,
                                                    CancellationToken cancellationToken = default(CancellationToken))
        {
            // Hash the password first.
            var hashedPassword = _encryptionService.Md5Hash(model.Password);

            // Search for account which is active and information is correct.
            var users = _unitOfWork.Accounts.Search();

            users = users.Where(x =>
                                x.Email.Equals(model.Email, StringComparison.InvariantCultureIgnoreCase) &&
                                x.Password.Equals(hashedPassword, StringComparison.InvariantCultureIgnoreCase) &&
                                x.Type == UserKind.Basic);

            // Find the first account in database.
            var user = await users.FirstOrDefaultAsync(cancellationToken);

            if (user == null)
            {
                throw new ApiException(HttpMessages.AccountIsNotFound, HttpStatusCode.NotFound);
            }

            switch (user.Status)
            {
            case UserStatus.Pending:
                throw new ApiException(HttpMessages.AccountIsPending, HttpStatusCode.Forbidden);

            case UserStatus.Disabled:
                throw new ApiException(HttpMessages.AccountIsDisabled, HttpStatusCode.Forbidden);
            }

            return(user);
        }
Exemplo n.º 2
0
        public void Configure(EntityTypeBuilder <User> builder)
        {
            builder.HasKey(x => x.Id);
            builder.Property(x => x.Username).IsRequired();
            builder.Property(x => x.Email).IsRequired();

            var users      = new List <User>();
            var linhNguyen = new User(Guid.NewGuid(), "linh.nguyen");

            linhNguyen.HashedPassword = _encryptionService.Md5Hash("administrator");
            linhNguyen.Kind           = UserKinds.Basic;
            linhNguyen.Status         = UserStatuses.Active;
            users.Add(linhNguyen);

            var alakanzam = new User(Guid.NewGuid(), "*****@*****.**");

            alakanzam.Kind   = UserKinds.Google;
            alakanzam.Status = UserStatuses.Active;
            users.Add(alakanzam);

            builder.HasData(users.ToArray());
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (await _clientStore.IsPkceClientAsync(context.ClientId))
                    {
                        // if the client is PKCE then we assume it's native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(View("Redirect", new RedirectViewModel {
                            RedirectUrl = model.ReturnUrl
                        }));
                    }

                    return(Redirect(model.ReturnUrl));
                }

                // since we don't have a valid context, then we just go back to the home page
                return(Redirect("~/"));
            }

            if (ModelState.IsValid)
            {
                // validate username/password against in-memory store
                //if (_users.ValidateCredentials(model.Username, model.Password))
                //{
                var hashedPassword = _encryptionService.Md5Hash(model.Password);
                var users          = _dbContext.Users.AsQueryable();

                var user = await users.Where(x =>
                                             x.Username.Equals(model.Username, StringComparison.InvariantCultureIgnoreCase) &&
                                             x.HashedPassword.Equals(hashedPassword, StringComparison.InvariantCultureIgnoreCase))
                           .FirstOrDefaultAsync();

                if (user == null)
                {
                    throw new Exception("Username or password is incorrect");
                }

                await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.Id.ToString("D"), user.Username));

                // only set explicit expiration here if user chooses "remember me".
                // otherwise we rely upon expiration configured in cookie middleware.
                AuthenticationProperties props = null;
                if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                {
                    props = new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                    };
                }
                ;

                // issue authentication cookie with subject ID and username
                await HttpContext.SignInAsync(user.Id.ToString("D"), user.Username, props);

                if (context != null)
                {
                    if (await _clientStore.IsPkceClientAsync(context.ClientId))
                    {
                        // if the client is PKCE then we assume it's native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(View("Redirect", new RedirectViewModel {
                            RedirectUrl = model.ReturnUrl
                        }));
                    }

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    return(Redirect(model.ReturnUrl));
                }

                // request for a local page
                if (Url.IsLocalUrl(model.ReturnUrl))
                {
                    return(Redirect(model.ReturnUrl));
                }
                else if (string.IsNullOrEmpty(model.ReturnUrl))
                {
                    return(Redirect("~/"));
                }
                else
                {
                    // user might have clicked on a malicious link - should be logged
                    throw new Exception("invalid return URL");
                }
                //}

                //await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));
                //ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }