Exemple #1
0
        public UpdateResult SetNewPassword(string accountID, string newPassword, string oldPassword, bool verifyOldPassword)
        {
            return(Execute(context =>
            {
                Guid accountId = BaseModel.DecryptId(accountID);
                Data.Account account = context.Accounts.SingleOrDefault(a => a.AccountId == accountId);
                if (account == null)
                {
                    return new UpdateResult("Invalid user");
                }

                if (verifyOldPassword)
                {
                    if (account.Password != MD5.Hex(oldPassword))
                    {
                        return new UpdateResult("Invalid old password");
                    }
                }

                account.Password = MD5.Hex(newPassword);
                if (!verifyOldPassword)
                {
                    account.ResetBySuperAdmin = true;
                }
                context.SaveChanges();

                return new UpdateResult(true);
            }));
        }
Exemple #2
0
        /// <summary>
        /// Change account password.
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task ChangePasswordAsync(string accountId, ChangedPassword model)
        {
            Data.Account account = await _store.LoadByGuid(accountId);

            if (account == null)
            {
                throw new AuthenticationFailureException();
            }

            if (account.Status == AccountStatus.Disabled)
            {
                throw new AccountDisabledException();
            }

            if (!IsPasswordComplex(model.Value))
            {
                throw new PasswordComplexityException();
            }

            if (account.HasHistoricalPassword(model.Value, _options.Password.History))
            {
                throw new PasswordHistoryException();
            }

            if (account.Tokens.Any(t => t.Type == AccountTokenType.Password) &&
                !account.VerifyPassword(model.CurrentPassword))
            {
                throw new AuthenticationFailureException();
            }

            await UpdatePasswordAsync(account, model.Value);
        }
Exemple #3
0
        private async Task <Data.Account> GetValidAccountAsync(Credentials creds)
        {
            Data.Account account = await _store.LoadByToken(creds.Username);

            if (account == null)
            {
                throw new AuthenticationFailureException();
            }

            if (account.Status == AccountStatus.Disabled)
            {
                throw new AccountDisabledException();
            }

            if (account.IsLocked())
            {
                string duration = account.LockDurationSeconds().ToString();
                throw new AccountLockedException(duration);
            }

            if (account.HasExpiredPassword(_options.Password.Age))
            {
                throw new PasswordExpiredException();
            }

            if (!account.VerifyPassword(creds.Password))
            {
                account.Lock(_options.Authentication.LockThreshold);
                await _store.Update(account);

                throw new AuthenticationFailureException();
            }

            return(account);
        }
Exemple #4
0
        public async Task <Account> RegisterUsername(string userMailto, string password, string globalId = null)
        {
            var registration = new UsernameRegistration(userMailto);

            Data.Account account = await Register(
                registration.Username,
                registration.DisplayName,
                AccountTokenType.Credential,
                registration.IsAffiliate,
                globalId ?? Guid.NewGuid().ToString()
                );

            if (_options.Registration.StoreEmail && registration.Username.IsEmailAddress())
            {
                UpdateProperty(account, ClaimTypes.Email, registration.Username);
                await _store.Update(account);
            }

            if (password.HasValue())
            {
                await UpdatePasswordAsync(account, password);
            }

            return(Mapper.Map <Account>(account, opts => {
                opts.Items["serviceUrl"] = _serviceUrl;
                opts.Items["profileOptions"] = _options.Profile;
            }));
        }
Exemple #5
0
        public UpdateResult SetActiveStatus(string id, bool active, string lastUpdateUsername)
        {
            return(Execute(context =>
            {
                Guid lastUpdateAccountId = context.Accounts.Single(a => a.Username == lastUpdateUsername).AccountId;

                Guid accountId = BaseModel.DecryptId(id);

                if (lastUpdateAccountId == accountId)
                {
                    return new UpdateResult("Cannot update your own status");
                }

                Models.ListItem listItem = DataAccess.ListItem.GetListItem("Status", active ? "Active" : "InActive");

                Data.Account account = context.Accounts.Single(acc => acc.AccountId == accountId);

                account.StatusId = listItem.GUID;

                WriteAudit(context, lastUpdateAccountId);
                account.LastUpdateAccountId = account.AccountId;
                account.LastUpdateTimestamp = DateTime.Now;

                context.SaveChanges();

                return new UpdateResult(true);
            }));
        }
Exemple #6
0
        public async Task SaveProfile(AccountProfile model)
        {
            Data.Account account = await _store.LoadByGuid(model.GlobalId);

            if (account != null)
            {
                if (model.Name.HasValue())
                {
                    UpdateProperty(account, ClaimTypes.Name, model.Name);
                }
                UpdateProperty(account, ClaimTypes.Biography, model.Biography);
                UpdateProperty(account, ClaimTypes.Org, model.Org);
                UpdateProperty(account, ClaimTypes.Unit, model.Unit);

                string logo = Path.GetFileName(model.OrgLogo).Before('?');
                if (logo == _options.Profile.DefaultLogo)
                {
                    logo = "";
                }
                UpdateProperty(account, ClaimTypes.OrgLogo, logo);

                logo = Path.GetFileName(model.UnitLogo).Before('?');
                if (logo == _options.Profile.DefaultLogo)
                {
                    logo = "";
                }
                UpdateProperty(account, ClaimTypes.UnitLogo, logo);

                account.UpdatedAt = DateTime.UtcNow;
                await _store.Update(account);
            }
        }
Exemple #7
0
        public async Task <Account> AuthenticateWithValidatedSubjectAsync(string subject, string location)
        {
            var detail = new CertificateSubjectDetail(subject);

            Data.Account account = await _store.LoadByToken(detail.ExternalId);

            if (account == null)
            {
                if (detail.DeprecatedExternalId.HasValue())
                {
                    account = await _store.LoadByToken(detail.DeprecatedExternalId);

                    if (account != null)
                    {
                        var token = account.Tokens.Where(t => t.Hash == detail.DeprecatedExternalId.ToNormalizedSha256()).Single();
                        account.Tokens.Remove(token);
                        account.Tokens.Add(new Data.AccountToken
                        {
                            Type        = AccountTokenType.Certificate,
                            Hash        = detail.ExternalId.ToNormalizedSha256(),
                            WhenCreated = DateTime.UtcNow,
                        });

                        await _store.Update(account);
                    }
                }

                if (account == null)
                {
                    account = await Register(detail.ExternalId, detail.DisplayName, AccountTokenType.Certificate, detail.IsAffiliate);
                }
            }

            return(await CompleteAuthentication(account, location));
        }
Exemple #8
0
        /// <summary>
        /// Add a certificate to an existing account.
        /// </summary>
        /// <param name="certificateToken"></param>
        /// <param name="name"></param>
        /// <param name="creds"></param>
        /// <returns></returns>
        /// <remarks>
        ///
        /// </remarks>
        protected async Task <Account> AddCertificateToken(string accountId, string certificateToken)
        {
            Data.Account account = await _store.LoadByGuid(accountId);

            if (account == null)
            {
                throw new AuthenticationFailureException();
            }

            if (account.Status == AccountStatus.Disabled)
            {
                throw new AccountDisabledException();
            }

            if (!await IsTokenUniqueAsync(certificateToken))
            {
                throw new AccountNotUniqueException();
            }

            account.Tokens.Add(new Data.AccountToken
            {
                Type        = AccountTokenType.Certificate,
                Hash        = certificateToken.ToNormalizedSha256(),
                WhenCreated = DateTime.UtcNow
            });

            await _store.Update(account);

            return(await CompleteAuthentication(account, ""));
        }
Exemple #9
0
        public async Task <Account> AuthenticateWithCodeAsync(Credentials creds, string location, Func <string, string, Task <bool> > dupeChecker = null)
        {
            Data.Account account = await _store.LoadByToken(creds.Username);

            if (account == null)
            {
                throw new AuthenticationFailureException();
            }

            if (account.Status == AccountStatus.Disabled)
            {
                throw new AccountDisabledException();
            }

            if (account.IsLocked())
            {
                string duration = account.LockDurationSeconds().ToString();
                _logger.LogDebug("{0} lock duration is {1}", account.Id, duration);
                throw new AccountLockedException(duration);
            }

            if (!await ValidateAccountCodeAsync(creds.Username, creds.Code) &&
                !(await ValidateAccountTOTPAsync(account.GlobalId, creds.Code, dupeChecker)).Valid)
            {
                account.Lock(_options.Authentication.LockThreshold);
                await _store.Update(account);

                throw new AccountTokenInvalidException();
            }

            return(await CompleteAuthentication(account, location));
        }
Exemple #10
0
        public Account(Data.Account data)
        {
            List <Permission> permissions = new List <Permission>();

            foreach (var perm in data.FunderAccountPermissions)
            {
                permissions.Add((Permission)perm);
            }
            foreach (var perm in data.ProviderAccountPermissions)
            {
                permissions.Add((Permission)perm);
            }

            Username           = data.Username;
            FirstName          = data.FirstName;
            LastName           = data.LastName;
            EmailAddress       = data.EmailAddress;
            Status             = data.Status.Name;
            Permissions        = permissions;
            ID                 = EncryptId(data.AccountId);
            Age                = data.LastUpdateTimestamp.Ticks;
            RegistrationNumber = data.RegistrationNumber;
            PracticeNumber     = data.PracticeNumber;
            ProfessionalBody   = data.ProfessionalBodyId;
        }
        public async Task <bool> Handle(AccountEditRequest request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var account = await context.AccountSet.FirstOrDefaultAsync(it => it.Id == request.Id, cancellationToken);

            // check if we aren't editing someone else's account
            if (account != null && account.UserId != request.UserId)
            {
                return(false);
            }

            // new account, otherwise we're editing our existing one
            if (account == null)
            {
                account = new Data.Account
                {
                    UserId  = request.UserId,
                    Created = DateTime.UtcNow
                };

                await context.AccountSet.AddAsync(account, cancellationToken);
            }

            account.Name = request.Name;
            account.IBAN = request.IBAN;

            await context.SaveChangesAsync(cancellationToken);

            return(true);
        }
Exemple #12
0
        /// <summary>
        /// Removes an account token (email address, certificate id)
        /// if it isn't the last one. Not recommended.
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="accountName"></param>
        /// <returns></returns>
        public async Task RemoveAccountAsync(int accountId, string accountName)
        {
            Data.Account account = await _store.Load(accountId);

            if (account == null)
            {
                throw new AccountNotFoundException();
            }

            if (account.Tokens.Count(t =>
                                     t.Type == AccountTokenType.Certificate ||
                                     t.Type == AccountTokenType.Credential
                                     ) < 2
                )
            {
                throw new AccountRemovalException();
            }

            var token = account.Tokens
                        .Where(t =>
                               t.Hash == accountName.ToNormalizedSha256() ||
                               t.Hash == accountName.ToNormalizedSha1()
                               ).SingleOrDefault();

            if (token != null)
            {
                account.Tokens.Remove(token);
                await _store.Update(account);
            }
        }
        public static void S2C_CHARACTER_LIST(GameConnection conn, Data.Account account)
        {
            var characters          = GameServer.Instance.ASDDatabase.GetCharacterList(account.Username).ToList();
            var characterListPacket = new MSG_S2C_CHARACTER_LIST();

            for (var i = 0; i < 5; i++)
            {
                if (i < characters.Count)
                {
                    characterListPacket.CharInfo[i] = new CHARACTER_INFO();
                    characterListPacket.CharInfo[i].CharacterName = characters[i].c_id;
                    characterListPacket.CharInfo[i].Used          = 1;
                    characterListPacket.CharInfo[i].Town          = 0;
                    characterListPacket.CharInfo[i].Class         = Convert.ToByte(characters[i].c_sheaderb);
                    characterListPacket.CharInfo[i].Level         = Convert.ToUInt32(characters[i].c_sheaderc);
                    characterListPacket.CharInfo[i].WearList      = new MSG_ITEM_WEAR[10];
                    var itemArray = characters[i].GetWear().Replace("_1WEAR=", string.Empty).Split(';');
                    var wearIndex = 0;
                    for (var j = 0; j < itemArray.Length; j += 3)
                    {
                        if (wearIndex == 10)
                        {
                            break;
                        }

                        if (!decimal.TryParse(itemArray[j], out _))
                        {
                            continue;
                        }

                        if (!GameServer.Instance.GameData.Items.ContainsKey(Convert.ToUInt32(itemArray[j]) & 0x3FFF))
                        {
                            continue;
                        }

                        uint option = 0;
                        if (decimal.TryParse(itemArray[j + 1], out _))
                        {
                            option = Convert.ToUInt32(itemArray[j + 1]);
                        }

                        characterListPacket.CharInfo[i].WearList[wearIndex]            = new MSG_ITEM_WEAR();
                        characterListPacket.CharInfo[i].WearList[wearIndex].ItemPtr    = 0;
                        characterListPacket.CharInfo[i].WearList[wearIndex].ItemCode   = Convert.ToUInt32(itemArray[j]);
                        characterListPacket.CharInfo[i].WearList[wearIndex].ItemOption = option;
                        characterListPacket.CharInfo[i].WearList[wearIndex].WearSlot   = GameServer.Instance.GameData.Items[Convert.ToUInt32(itemArray[j]) & 0x3FFF].SlotIndex;
                        wearIndex++;
                    }
                }
                else
                {
                    characterListPacket.CharInfo[i]       = new CHARACTER_INFO();
                    characterListPacket.CharInfo[i].Class = 255;
                }
            }

            conn.Send(characterListPacket.Serialize());
        }
Exemple #14
0
        public int CreateAccount(AccountInfo accountInfo)
        {
            Data.Account account = ConvertToDb(accountInfo);

            _context.Accounts.Add(account);
            _context.SaveChanges();

            return(account.Id);
        }
Exemple #15
0
 private void UpdateExternalUserProfile(Data.Account account, ClaimsPrincipal principal)
 {
     UpdateProperty(account, ClaimTypes.Name, principal.FindFirst(ClaimTypes.Name)?.Value);
     UpdateProperty(account, ClaimTypes.Avatar, principal.FindFirst(ClaimTypes.Avatar)?.Value);
     UpdateProperty(account, ClaimTypes.Org, principal.FindFirst(ClaimTypes.Org)?.Value);
     UpdateProperty(account, ClaimTypes.IdAffiliate, principal.FindFirst(ClaimTypes.IdAffiliate)?.Value);
     UpdateProperty(account, ClaimTypes.Unit, principal.FindFirst(ClaimTypes.Unit)?.Value);
     UpdateProperty(account, ClaimTypes.OrgLogo, principal.FindFirst(ClaimTypes.OrgLogo)?.Value);
     UpdateProperty(account, ClaimTypes.UnitLogo, principal.FindFirst(ClaimTypes.UnitLogo)?.Value);
 }
Exemple #16
0
        public async Task SetProperties(int accountId, AccountProperty[] props)
        {
            Data.Account account = await _store.Load(accountId);

            foreach (var prop in props)
            {
                UpdateProperty(account, prop.Key, prop.Value);
            }
            await _store.Update(account);
        }
Exemple #17
0
        public async Task <Account> FindByAccountAsync(string accountName)
        {
            Data.Account account = await _store.LoadByToken(accountName);

            return((account != null)
                ? Mapper.Map <Account>(account, opts => {
                opts.Items["serviceUrl"] = _serviceUrl;
                opts.Items["profileOptions"] = _options.Profile;
            })
                : null);
        }
Exemple #18
0
        public async Task <Account> FindAsync(int id)
        {
            Data.Account account = await _store.Load(id);

            return((account != null)
                ? Mapper.Map <Account>(account, opts => {
                opts.Items["serviceUrl"] = _serviceUrl;
                opts.Items["profileOptions"] = _options.Profile;
            })
                : null);
        }
Exemple #19
0
        public async Task <AlternateAccountProfile> FindAlternateProfile(string guid)
        {
            Data.Account account = await _store.LoadByGuid(guid);

            return((account != null)
                ? Mapper.Map <AlternateAccountProfile>(account, opts => {
                opts.Items["serviceUrl"] = _serviceUrl;
                opts.Items["profileOptions"] = _options.Profile;
            })
                : new AlternateAccountProfile());
        }
Exemple #20
0
        protected async Task <Account> CompleteAuthentication(Data.Account account, string location)
        {
            account.SetAuthenticated(location);
            OnUserAuthenticated(account);
            await _store.Update(account);

            return(Mapper.Map <Account>(account, opts => {
                opts.Items["serviceUrl"] = _serviceUrl;
                opts.Items["profileOptions"] = _options.Profile;
            }));
        }
Exemple #21
0
        public int Add(Data.Account account)
        {
            if (account == null)
            {
                return(-1);
            }
            var context = new DataContext();

            context.Account.Add(account);
            context.SaveChanges();
            return(account.ID);
        }
Exemple #22
0
        public PlayerController(Client player)
        {
            this.AccountData   = new Data.Account();
            this.CharacterData = new Data.Character();

            this.player            = player;
            this.muted             = true;
            this.LoggedIn          = false;
            this.SelectedCharacter = false;

            EntityManager.Add(this);
        }
Exemple #23
0
        public async Task <AccountProfile> FindProfile(string guid, bool isSelf = false)
        {
            Data.Account account = await _store.LoadByGuid(guid);

            // TODO: consider returning filtered claims here
            return((account != null && (isSelf || account.IsPublic || _options.Profile.ForcePublic))
                ? Mapper.Map <AccountProfile>(account, opts => {
                opts.Items["serviceUrl"] = _serviceUrl;
                opts.Items["profileOptions"] = _options.Profile;
            })
                : new AccountProfile());
        }
Exemple #24
0
        public async Task SetRole(int accountId, AccountRole role)
        {
            Data.Account account = await _store.Load(accountId);

            if (account == null)
            {
                throw new AccountNotFoundException();
            }

            account.Role = role;

            await _store.Update(account);
        }
Exemple #25
0
        public async Task Unlock(int accountId)
        {
            Data.Account account = await _store.Load(accountId);

            if (account == null)
            {
                throw new AccountNotFoundException();
            }

            account.Unlock();

            await _store.Update(account);
        }
Exemple #26
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            // создать профиль получить айди всунуть его в добавляемую модель и изменить ретернЮРЛ на ссылку профиля ура

            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var profile = new User()
                {
                    Email    = Input.Email, FirstName = Input.FirstName,
                    LastName = Input.LastName, ShortName = Input.ShortName
                };
                int profileId = await _gate.AddUser(profile);

                if (profileId != 0)
                {
                    var user = new Data.Account {
                        UserName = Input.Email, Email = Input.Email, ProfileId = profileId
                    };
                    returnUrl = Url.Content("~/profiles/" + profileId.ToString());
                    var result = await _userManager.CreateAsync(user, Input.Password);

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created a new account with password.");

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { userId = user.Id, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                          $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemple #27
0
        private async Task UpdatePasswordAsync(Data.Account account, string password)
        {
            account.TrimPasswordHistory(_options.Password.History);
            await _store.Update(account);

            account.Tokens.Add(new Data.AccountToken
            {
                UserId      = account.Id,
                Hash        = account.GeneratePasswordHash(password),
                WhenCreated = DateTime.UtcNow,
                Type        = AccountTokenType.Password
            });
            await _store.Update(account);
        }
Exemple #28
0
        public static bool Add(Data.Account account)
        {
            bool result = false;

            if (account == null)
            {
                return(result);
            }
            var context = new DataContext();

            context.Account.Add(account);
            context.SaveChanges();
            return(result);
        }
Exemple #29
0
        public async Task ClearPassword(string accountId)
        {
            Data.Account account = await _store.LoadByGuid(accountId);

            if (account == null)
            {
                throw new AuthenticationFailureException();
            }

            foreach (var token in account.Tokens.Where(t => t.Type == AccountTokenType.Password).ToArray())
            {
                account.Tokens.Remove(token);
            }

            await _store.Update(account);
        }
Exemple #30
0
        public async Task <Account> RegisterWithValidatedSubjectAsync(string subject)
        {
            var detail = new CertificateSubjectDetail(subject);

            Data.Account account = await Register(
                detail.ExternalId,
                detail.DisplayName,
                AccountTokenType.Certificate,
                detail.IsAffiliate
                );

            return(Mapper.Map <Account>(account, opts => {
                opts.Items["serviceUrl"] = _serviceUrl;
                opts.Items["profileOptions"] = _options.Profile;
            }));
        }
        private async void _HandleAdministrator()
        {
            var accounts = await this._Database.Find<Data.Account>(a => a.Name == this._DefaultAdministratorName);

            if (accounts.Count == 0)
            {
                var account = new Data.Account
                {
                    Id = Guid.NewGuid(),
                    Name = this._DefaultAdministratorName,
                    Password = "******",
                    Competnces = Data.Account.AllCompetnce()
                };

                await this._Database.Add(account);

                
            }
        }