Beispiel #1
0
        public async Task <BearerToken> GenerateTokenAsync(string username, string password, string membershipId, bool fireEvent = true)
        {
            // Check membership
            var membership = await this.membershipService.GetAsync(membershipId);

            if (membership == null)
            {
                throw ErtisAuthException.MembershipNotFound(membershipId);
            }

            if (!membership.IsValid(out IEnumerable <string> errors))
            {
                throw ErtisAuthException.MalformedMembership(membershipId, errors);
            }

            // Check user
            var user = await this.userService.GetUserWithPasswordAsync(username, username, membership.Id);

            if (user == null)
            {
                throw ErtisAuthException.UserNotFound(username, "username or email");
            }

            // Check password
            var passwordHash = this.cryptographyService.CalculatePasswordHash(membership, password);

            if (passwordHash != user.PasswordHash)
            {
                throw ErtisAuthException.UsernameOrPasswordIsWrong(username, password);
            }
            else
            {
                var token = this.GenerateBearerToken(user, membership);

                if (fireEvent)
                {
                    await this.eventService.FireEventAsync(this, new ErtisAuthEvent(ErtisAuthEventType.TokenGenerated, user, token));
                }

                return(token);
            }
        }