public async Task <UserValidationResponse> SignIn(CredentialsModel credentialsModel)
        {
            try
            {
                var user = await Find(credentialsModel.Email);

                if (user == null)
                {
                    return(new UserValidationResponse(false, UserValidationResponseMessage.UserDoesNotExist));
                }

                var result = PasswordHasher.VerifyPassword(credentialsModel, user);

                if (result)
                {
                    return(new UserValidationResponse(true, UserValidationResponseMessage.SignedIn,
                                                      m_authentication.CreateToken(user)));
                }

                return(new UserValidationResponse(false, UserValidationResponseMessage.InvalidPassword));
            }
            catch (Exception e)
            {
                m_logger.LogError(e, "couldn't sign in");
                return(new UserValidationResponse(false));
            }
        }
Beispiel #2
0
        public static string Login(CredentialsModel value)
        {
            using (var dbContext = new FiszkiContext())
            {
                var user = dbContext.Users.FirstOrDefault(x => x.Login == value.Login);
                if (user == null)
                {
                    return(null);
                }

                if (user.Password != value.Password)
                {
                    dbContext.UsersLogs.Add(new Repositories.UserLogs   //Dodanie informacji o logowaniu + złe hasło
                    {
                        UserId      = user.Id,
                        LoginDate   = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), // Data rejestracji
                        LoginStatus = "Nieprawidłowe hasło"
                                                                                    //var x = UserLogsRepository.AddUserLogsList(user.Id, )
                    });
                    dbContext.SaveChanges();

                    return(null);
                }

                dbContext.UsersLogs.Add(new Repositories.UserLogs   //Dodanie informacji o logowaniu + złe hasło
                {
                    UserId      = user.Id,
                    LoginDate   = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), // Data rejestracji
                    LoginStatus = "Zalogowano"
                });
                dbContext.SaveChanges();

                return(JWTService.GenerateToken(user.Id));
            }
        }
Beispiel #3
0
        public async Task <TokenResponse> AuthenticateUserAsync(CredentialsModel model)
        {
            var user = await this.userManager.FindByEmailAsync(model.Email);

            var isPasswordCorrect = await this.userManager.CheckPasswordAsync(user, model.Password);

            if (user == null || !isPasswordCorrect)
            {
                throw new UserAuthenticationException("Unauthorized");
            }

            var token = await this.GenerateUserToken(user);

            var accessToken = new JwtSecurityTokenHandler().WriteToken(token);

            var result = new TokenResponse
            {
                UserEmail   = user.Email,
                Type        = "bearer",
                AccessToken = accessToken,
                Expiration  = token.ValidTo
            };

            return(result);
        }
        public async Task <ActionResult <AuthResponse> > Login([FromBody] CredentialsModel credentialsVM)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new AuthResponse {
                    success = true, token = "", message = ModelState.ToString()
                }));
            }

            AuthenticateServiceResult result = await _accountService.AuthenticateAsync(credentialsVM.Email, credentialsVM.Password, _jwtOptions.Value.ExpiresInMinutes,
                                                                                       _jwtOptions.Value.ValidIssuer, _jwtOptions.Value.ValidAudience, _jwtOptions.Value.SymmetricSecurityKey);

            //if (result == null)
            //    return BadRequest(new AuthResponse { success = false, token = "", message = "Username or password is incorrect" });

            if (result == null)
            {
                return(Unauthorized());
            }

            return(new AuthResponse {
                success = true,
                token = result.Token,
                expiresInMinutes = _jwtOptions.Value.ExpiresInMinutes,
                message = "Success!",
                email = credentialsVM.Email,
                role = result.Role
            });
        }
        private bool ValidateCredentials(CredentialsModel credentialsModel)
        {
            CredentialsModelValidator validator = new CredentialsModelValidator();

            FluentValidation.Results.ValidationResult result = validator.Validate(credentialsModel);
            return(result.IsValid);
        }
        private bool ConnectWithCredentials(CredentialsModel credentialsModel)
        {
            _vssConnection = GetVssConnection(credentialsModel);

            try
            {
                _vssConnection.ConnectAsync().SyncResult();
            }
            catch (Exception ex)
            {
                _console.ErrorMessage(ex.Message);
            }

            if (_vssConnection.HasAuthenticated)
            {
                AccountName         = credentialsModel.AccountName;
                Project             = credentialsModel.Project;
                PersonalAccessToken = credentialsModel.PersonalAccessToken;

                _cacheService.CacheConnection(credentialsModel);
                return(true);
            }

            return(false);
        }
        public ApiResponse <CredentialsModel> Post([FromRoute] Guid packageId, [FromBody] CredentialsModel request)
        {
            // Create the response object
            ApiResponse <CredentialsModel> response = new ApiResponse <CredentialsModel>();

            // Map the model to a domain object type
            Credentials savedCredentials = mapper.Map <Credentials>(request);

            // Did the mapping work ok?
            if (savedCredentials != null)
            {
                // Did we find a package?
                Package package = SessionHandler.PackageRepository.Get(packageId);
                if (package != null)
                {
                    // Get the repository to save the package for us
                    savedCredentials = package.Save <Credentials>(savedCredentials);
                }

                // Saved ok?
                if (savedCredentials != null)
                {
                    // Map the data definition back to a model type and send it back to the user
                    response.Data = mapper.Map <CredentialsModel>(savedCredentials);
                }

                // Nothing died .. Success
                response.Success = true;
            }

            // Send the response back
            return(response);
        }
Beispiel #8
0
        public IActionResult Signin([FromBody] CredentialsModel credentials)
        {
            if (CheckFieldsError())
            {
                return(BadRequest(ErrorResponse.CreateErrorResponse("Invalid fields", 3)));
            }

            if (credentials == null || string.IsNullOrWhiteSpace(credentials.Email) || string.IsNullOrWhiteSpace(credentials.Password))
            {
                return(BadRequest(ErrorResponse.CreateErrorResponse("Missing fields", 4)));
            }

            UserEntity user = _userService.Signin(credentials.Email, credentials.Password);

            if (user != null)
            {
                SigninDto dto = new SigninDto
                {
                    UserId    = user.UserId,
                    FirstName = user.FirstName,
                    LastName  = user.LastName,
                    Email     = user.Email,
                    Password  = user.Password,
                    Phones    = user.Phones
                };
                return(Ok(Crosscutting.Response.CreateResponse(dto)));
            }
            else
            {
                return(Ok(ErrorResponse.CreateErrorResponse("Invalid e-mail or password", 5)));
            }
        }
Beispiel #9
0
        public async Task <ActionResult <string> > Token([Required] CredentialsModel model)
        {
            var user = await UserManager.FindByNameAsync(model.Username);

            if (user == null)
            {
                return(StatusCode(401, new { msg = "auth.error.user-or-pass-mismatch" }));
            }

            var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, true);

            if (!result.Succeeded)
            {
                return(StatusCode(401, new { msg = "auth.error.user-or-pass-mismatch" }));
            }
            else if (result.IsLockedOut)
            {
                return(StatusCode(401, new { msg = "auth.error.locked-out", args = new[] { user.LockoutUntil } }));
            }
            else if (result.RequiresTwoFactor || result.IsNotAllowed)
            {
                return(StatusCode(500, $"wrongly configured signin; result is {result}"));
            }

            return(Ok(Settings.GenerateToken(user)));
        }
        private VssConnection GetVssConnection(CredentialsModel credentialsModel)
        {
            var baseUrl     = new Uri(String.Format("https://{0}.visualstudio.com", credentialsModel.AccountName));
            var credentials = new VssBasicCredential(string.Empty, credentialsModel.PersonalAccessToken);

            return(new VssConnection(baseUrl, credentials));
        }
        public async Task <IActionResult> ChangePassword(string userId,
                                                         [FromBody] CredentialsModel userCredentials)
        {
            try
            {
                var user = await Client.Users.GetUserAsync(userId);

                if (user == null)
                {
                    return(BadRequest("Invalid User"));
                }

                var credentials = await user.ChangePasswordAsync(new ChangePasswordOptions()
                {
                    CurrentPassword = userCredentials.CurrentPassword,
                    NewPassword     = userCredentials.NewPassword
                });

                if (credentials == null)
                {
                    return(BadRequest());
                }

                return(Ok());
            }
            catch (System.Exception e)
            {
                // TODO: log the exception and return human-friendly message
                return(StatusCode(500, e.Message));
            }
        }
Beispiel #12
0
 public async Task <IActionResult> Post([FromBody] CredentialsModel credentials)
 {
     if (!ModelState.IsValid)
     {
         return(BadRequest(ModelState));
     }
     var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password);
 }
        public async Task <IActionResult> Post([FromBody] CredentialsModel credentials)
        {
            m_logger.LogDebug($"Try create user {credentials.Email}");
            var response = await m_userRepository.Create(credentials.Email, credentials.Password);

            m_logger.LogDebug($"{response.Succeeded} {response.Message}");
            return(Ok(response));
        }
 public CredentialsViewModel()
 {
     _loginCredentialsModel = new CredentialsModel();
     _loginCommand          = new RelayCommand(Login, CanExecuteCredentials);
     _registerCommand       = new RelayCommand(SignUp, CanExecuteCredentials);
     _transferLoginCommand  = new RelayCommand(TransferLogin, o => true);
     _transferSignUpCommand = new RelayCommand(TransferSignUp, o => true);
 }
        public async Task <IActionResult> Token([FromBody] CredentialsModel credentials)
        {
            var response = await(await new TokensAuthenticationModel()
                                 .AddAccessToken(credentials, _tokenHelper))
                           .AddRefreshTokenFields(credentials.UserName, _refreshTokenHelper);

            return(Ok(response));
        }
        public async Task <IActionResult> Get([FromBody] CredentialsModel credentialsModel)
        {
            m_logger.LogDebug($"Try sign-in user {credentialsModel.Email}");
            var response = await m_userRepository.SignIn(credentialsModel);

            m_logger.LogDebug($"{response.Succeeded} {response.Message}");

            return(Ok(response));
        }
Beispiel #17
0
        public async Task <ViewResult> Connect(CredentialsModel credentials)
        {
            _authenticationToken = AcquireOAuthAccessToken(credentials);
            var userSessionToken =
                await AcquireUserSessionToken(_authenticationToken, new Uri(credentials.UserSessionEndpoint));

            return(View("Widget",
                        new WidgetModel(userSessionToken, credentials.FullCDNPath, credentials.IndividualSummaryEndpoint)));
        }
        public static async Task <TokensAuthenticationModel> AddAccessToken(this TokensAuthenticationModel tokensAuthenticationModel,
                                                                            CredentialsModel credentials,
                                                                            TokenHelper tokenHelper)
        {
            tokensAuthenticationModel.AccessToken =
                await tokenHelper.GenerateToken(credentials.UserName, credentials.Password);

            return(tokensAuthenticationModel);
        }
Beispiel #19
0
        public static bool VerifyPassword(CredentialsModel credentialsModel, User user)
        {
            var passwordHash = Convert.ToBase64String(KeyDerivation.Pbkdf2(credentialsModel.Password, Convert.FromBase64String(user.Salt),
                                                                           KeyDerivationPrf.HMACSHA1,
                                                                           10000,
                                                                           256 / 8));

            return(passwordHash == user.PasswordHash);
        }
 public Task <Option <UserServiceModel, Error> > LoginAsync(CredentialsModel model) =>
 GetUser(u => u.Email == model.Email)
 .FilterAsync(user => UserManager.CheckPasswordAsync(user, model.Password), "Invalid credentials.".ToError())
 .MapAsync(async user =>
 {
     var result = Mapper.Map <UserServiceModel>(user);
     await SignInManager.SignInAsync(user, isPersistent: false);
     return(result);
 });
Beispiel #21
0
        public Task SaveCredentialsAsync(string teamId, CredentialsModel value)
        {
            var secret = new DbConnectionStringBuilder();

            secret.Add("username", value.Username);
            secret.Add("password", value.Password);
            secret.Add("baseAddress", value.BaseAddress);
            return(SaveSecretAsync(teamId, Providers.Jda, secret.ConnectionString));
        }
Beispiel #22
0
        private async Task <LoginModel> CreateLoginAsync(CredentialsModel model)
        {
            LoginModel vm = await CreateLoginAsync(model.ReturnUrl);

            vm.Username      = model.Username;
            vm.RememberLogin = model.RememberLogin;

            return(vm);
        }
Beispiel #23
0
        public Task SaveCredentialsAsync(CredentialsModel value)
        {
            var secret = new DbConnectionStringBuilder
            {
                { "username", value.Username },
                { "password", value.Password }
            };

            return(SaveSecretAsync(CredentialSecretName, secret.ConnectionString));
        }
Beispiel #24
0
 public ActionResult SoftwarePotentialCredentials(CredentialsModel credentials)
 {
     if (ModelState.IsValid)
     {
         var file = SoftwarePotentialConfiguration.File;
         file.WriteCredentials(credentials.Username, credentials.Password);
         return(RedirectToAction("Index", "Home"));
     }
     return(View(credentials));
 }
Beispiel #25
0
 public Startup(IConfiguration configuration)
 {
     Configuration     = configuration;
     _credentialsModel = new CredentialsModel
     {
         AccessKey = Configuration["vcap:services:user-provided:0:credentials:AccessKey"],
         SecretKey = Configuration["vcap:services:user-provided:0:credentials:SecretKey"],
         Region    = Configuration["vcap:services:user-provided:0:credentials:Region"]
     };
 }
Beispiel #26
0
 private static void TrimCredentialsModel(CredentialsModel credentials)
 {
     credentials.UserSessionEndpoint       = credentials.UserSessionEndpoint.Trim();
     credentials.Authority                 = credentials.Authority.Trim();
     credentials.ClientID                  = credentials.ClientID.Trim();
     credentials.ResourceID                = credentials.ResourceID.Trim();
     credentials.SecretKey                 = credentials.SecretKey.Trim();
     credentials.FullCDNPath               = credentials.FullCDNPath.Trim(' ', '/');
     credentials.IndividualSummaryEndpoint = credentials.IndividualSummaryEndpoint.Trim(' ', '/');
 }
        public ActionResult Index()
        {
            CredentialsModel model = new CredentialsModel
            {
                ClientID     = Config.AssurBoxApiClientID,
                ClientSecret = Config.AssurBoxApiClientSecret
            };

            return(View(model));
        }
Beispiel #28
0
        private void HandleAuthenticationRequiredMessage(AuthenticationRequiredMessage msg)
        {
            var model = new CredentialsModel {
                PromptMessage = msg.Message
            };
            var credentialsDialog = new CredentialsDialog(model);
            var dialogResult      = credentialsDialog.ShowDialog();

            msg.Callback(dialogResult, model.UserName, model.Password);
        }
Beispiel #29
0
        public async Task Create(CredentialsModel credentials)
        {
            var credentialsBL  = mapper.Map <CredentialsModelBL>(credentials);
            var identityResult = await accountsPort.Create(credentialsBL);

            if (!identityResult.Succeeded)
            {
                logger.LogWarning($"Failed to create account with username: {credentials.Username}. Identity result: {identityResult.ToString()}");
                throw new ApplicationIdentityException(identityResult);
            }
        }
        public CookieHttpHandler(JdaPersonaOptions options, CredentialsModel credentials, string teamId, bool expireToken = false)
        {
            _options     = options;
            _credentials = credentials;
            _teamId      = teamId;

            if (expireToken)
            {
                ExpireToken();
            }
        }