public async Task <KeyValuePair <bool, Account> > AuthenticateUserAccount([NotNull] AuthenticationVM authenticationData)
        {
            try {
                Account dbAccount = await _dbContext.Accounts.SingleOrDefaultAsync(
                    account => (
                        Helpers.IsProperString(authenticationData.Email)
                                       ? account.Email.ToLower().Equals(authenticationData.Email.ToLower())
                                       : account.Username.ToLower().Equals(authenticationData.Username.ToLower())
                        ) &&
                    account.EmailConfirmed == true &&
                    account.RecoveryToken == null &&
                    account.TokenSetOn == null
                    );

                return(dbAccount == null
                    ? new KeyValuePair <bool, Account>(true, null)
                    : new KeyValuePair <bool, Account>(true, dbAccount));
            }
            catch (InvalidOperationException e) {
                await _coreLogService.InsertRoutinizeCoreLog(new RoutinizeCoreLog {
                    Location            = $"{ nameof(AuthenticationService) }.{ nameof(AuthenticateUserAccount) }",
                    Caller              = $"{ new StackTrace().GetFrame(4)?.GetMethod()?.DeclaringType?.FullName }",
                    BriefInformation    = nameof(InvalidOperationException),
                    DetailedInformation = $"Error while retrieving an entry with SingleOrDefault, >1 entry matching predicate.\n\n{ e.StackTrace }",
                    ParamData           = $"{ nameof(authenticationData) } = { JsonConvert.SerializeObject(authenticationData) }",
                    Severity            = SharedEnums.LogSeverity.High.GetEnumValue()
                });

                return(new KeyValuePair <bool, Account>(false, null));
            }
        }
 public AuthenticationV()
 {
     InitializeComponent();
     BindingContext = new AuthenticationVM()
     {
         Navigation = this.Navigation
     };
 }
        public async Task <AuthenticationVM> GetTokenAsync(TokenRequestVM model)
        {
            var authenticationModel = new AuthenticationVM();

            var user = await _userManager.FindByEmailAsync(model.UserName);

            if (user == null)
            {
                user = await _userManager.FindByNameAsync(model.UserName);
            }


            if (user == null)
            {
                authenticationModel.IsAuthenticated = false;
                authenticationModel.Message         = $"Error, No accounts registered with {model.UserName}.";
                return(authenticationModel);
            }
            if (await _userManager.CheckPasswordAsync(user, model.Password))
            {
                JwtSecurityToken jwtSecurityToken = await CreateJwtToken(user);

                authenticationModel.IsAuthenticated = true;
                authenticationModel.Token           = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                authenticationModel.Email           = user.Email;
                authenticationModel.UserName        = user.UserName;
                authenticationModel.FirstName       = user.FirstName;
                authenticationModel.LastName        = user.LastName;
                var rolesList = await _userManager.GetRolesAsync(user).ConfigureAwait(false);

                authenticationModel.Roles = rolesList.ToList();


                if (user.RefreshTokens.Any(a => a.IsActive))
                {
                    var activeRefreshToken = user.RefreshTokens.Where(a => a.IsActive == true).FirstOrDefault();

                    authenticationModel.RefreshToken           = activeRefreshToken.Token;
                    authenticationModel.RefreshTokenExpiration = activeRefreshToken.Expires;
                }
                else
                {
                    var refreshToken = CreateRefreshToken();
                    authenticationModel.RefreshToken           = refreshToken.Token;
                    authenticationModel.RefreshTokenExpiration = refreshToken.Expires;

                    user.RefreshTokens.Add(refreshToken);
                    _context.Update(user);
                    _context.SaveChanges();
                }

                return(authenticationModel);
            }
            authenticationModel.IsAuthenticated = false;
            authenticationModel.Message         = $"Error, Incorrect Credentials for user {user.Email}.";
            return(authenticationModel);
        }
Esempio n. 4
0
        public override async Task <ApplicationUser> FindAsync(string userName, string password)
        {
            try
            {
                var ApiPath = ConfigurationManager.AppSettings["ApiPath"].ToString() + "api/";

                UserVM userWithPermissions = new UserVM();
                var    UserModel           = new AuthenticationVM()
                {
                    UserName = userName, Password = password
                };

                using (var client = new HttpClient())
                {
                    //   client.BaseAddress = new Uri("http://localhost:14529/api/");
                    client.BaseAddress = new Uri(ApiPath);

                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    //    var uri = "http://localhost:14529/api/Accounts/GetUserInfo";
                    var uri = ApiPath + "Accounts/GetUserInfo";

                    var response = await client.PostAsJsonAsync(uri, UserModel);

                    if (response.IsSuccessStatusCode)
                    {
                        userWithPermissions = await response.Content.ReadAsAsync <UserVM>();
                    }
                }
                if (userWithPermissions == null)
                {
                    userWithPermissions = new UserVM();
                }
                Task <ApplicationUser> user = Task <ApplicationUser> .Factory.StartNew(() =>
                {
                    return(new ApplicationUser()
                    {
                        Id = userWithPermissions.UserName,
                        FriendlyName = userWithPermissions.FriendlyName,
                        PrimaryEmail = userWithPermissions.PrimaryEmail,
                        Telephone = userWithPermissions.Telephone,
                        UserName = userWithPermissions.UserName,
                        IsJazz = userWithPermissions.IsJazz,
                        Permissions = userWithPermissions.Permissions
                    });
                });

                return(await user);
            }
            catch (Exception EX)
            {
                throw;
            }
        }
        public async Task <ActionResult <AuthenticationVM> > Refresh([FromBody] RefreshTokenCommand command)
        {
            AuthenticationVM authenticationVM = await CommandAsync(command);

            if (!authenticationVM.Success)
            {
                return(BadRequest(authenticationVM));
            }

            return(Ok(authenticationVM));
        }
Esempio n. 6
0
        private void CreateButton_Click(object sender, RoutedEventArgs e)
        {
            AuthenticationVM dc = (this.DataContext as AuthenticationVM);

            dc.IsPasswordMismatch = !ConfirmTextBox.Password.Equals(pass.Password);
            MainVM.Instance.IsActionInProgress = true;

            dc.InsertUser();
            if (dc.InvalidFirstName || dc.InvalidLastName || dc.InvalidEmailID || dc.InvalidPassword || dc.IsPasswordMismatch || dc.InvalidStudentID)
            {
                MainVM.Instance.IsActionInProgress = false;
                return;
            }
            this.Frame.Navigate(typeof(HomePage));
        }
        public async Task <AuthenticationVM> RefreshTokenAsync(string token)
        {
            var authenticationModel = new AuthenticationVM();
            var user = _context.Users.SingleOrDefault(u => u.RefreshTokens.Any(t => t.Token == token));

            if (user == null)
            {
                authenticationModel.IsAuthenticated = false;
                authenticationModel.Message         = $"Error, Token did not match any users.";
                return(authenticationModel);
            }

            var refreshToken = user.RefreshTokens.Single(x => x.Token == token);

            if (!refreshToken.IsActive)
            {
                authenticationModel.IsAuthenticated = false;
                authenticationModel.Message         = $"Error, Token Not Active.";
                return(authenticationModel);
            }

            //Revoke Current Refresh Token
            refreshToken.Revoked = DateTime.UtcNow;

            //Generate new Refresh Token and save to Database
            var newRefreshToken = CreateRefreshToken();

            user.RefreshTokens.Add(newRefreshToken);
            _context.Update(user);
            _context.SaveChanges();

            //Generates new jwt
            authenticationModel.IsAuthenticated = true;
            JwtSecurityToken jwtSecurityToken = await CreateJwtToken(user);

            authenticationModel.Token    = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            authenticationModel.Email    = user.Email;
            authenticationModel.UserName = user.UserName;
            var rolesList = await _userManager.GetRolesAsync(user).ConfigureAwait(false);

            authenticationModel.Roles                  = rolesList.ToList();
            authenticationModel.RefreshToken           = newRefreshToken.Token;
            authenticationModel.RefreshTokenExpiration = newRefreshToken.Expires;
            return(authenticationModel);
        }
        public async Task <ActionResult <AuthenticationVM> > Login([FromBody] LoginUserCommand command)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new AuthenticationVM
                {
                    Errors = ModelState.Values.SelectMany(x => x.Errors.Select(xx => xx.ErrorMessage))
                }));
            }

            AuthenticationVM authenticationVM = await CommandAsync(command);

            if (!authenticationVM.Success)
            {
                return(BadRequest(authenticationVM));
            }

            return(Ok(authenticationVM));
        }
Esempio n. 9
0
        public async Task <KeyValuePair <bool, AuthenticatedUser> > AuthenticateHidrogenian(AuthenticationVM auth)
        {
            _logger.LogInformation("AuthenticationService.AuthenticateHidrogenian - Service starts.");

            Hidrogenian hidrogenian;
            string      role;

            try {
                hidrogenian = await _dbContext.Hidrogenian.FirstOrDefaultAsync(
                    h => (auth.Email != null ? h.Email == auth.Email
                                             : h.UserName.ToLower() == auth.UserName
                          ) &&
                    h.EmailConfirmed &&
                    h.RecoveryToken == null &&
                    h.TokenSetOn == null
                    );

                role = await(from rc in _dbContext.RoleClaimer
                             join r in _dbContext.HidroRole
                             on rc.RoleId equals r.Id
                             where rc.HidrogenianId == hidrogenian.Id
                             select r.RoleName).FirstOrDefaultAsync();
            } catch (Exception e) {
                _logger.LogError("AuthenticationService.AuthenticateHidrogenian - Error: " + e);
                return(new KeyValuePair <bool, AuthenticatedUser>(false, null));
            }

            if (!BCryptHelper.CheckPassword(auth.Password, hidrogenian.PasswordHash))
            {
                return(new KeyValuePair <bool, AuthenticatedUser>(true, null));
            }

            var unixTimeStamp = ((DateTimeOffset)DateTime.UtcNow).ToUnixTimeSeconds();
            var authToken     = GenerateHashedPasswordAndSalt(hidrogenian.Id + hidrogenian.Email + unixTimeStamp);

            var profile = await _dbContext.HidroProfile.FirstOrDefaultAsync(p => p.HidrogenianId == hidrogenian.Id);

            var expirationTime = ((DateTimeOffset)DateTime.UtcNow.AddSeconds(
                                      auth.TrustedAuth ? HidroConstants.TRUSTED_AUTH_EXPIRATION_TIME : HidroConstants.INTRUSTED_AUTH_EXPIRATION_TIME
                                      )).ToUnixTimeSeconds();

            var avatar = profile.ProcessAvatarInfo();

            var authUser = new AuthenticatedUser {
                UserId         = hidrogenian.Id,
                Role           = role,
                AuthToken      = authToken.Key,
                Email          = hidrogenian.Email,
                UserName       = hidrogenian.UserName,
                FullName       = profile.GivenName + ' ' + profile.FamilyName,
                Avatar         = avatar?.Name,
                ExpirationTime = expirationTime
            };

            return(new KeyValuePair <bool, AuthenticatedUser>(true, authUser));
        }