public MemberToken CreateToken(MemberToken memberToken)
        {
            using (context = new DomainContext())
            {
                context.Configuration.LazyLoadingEnabled = false;

                context.MemberTokens.Add(memberToken);

                context.SaveChanges();
            }

            return memberToken;
        }
        public IHttpActionResult UpdateProfile(ProfileUpdateRequest request)
        {
            var response = new ProfileUpdateResponse();

            try
            {
                var isValidRequest = false;
                var emailChanged = false;

                var memberId = request.GetMemberId();

                var member = MembershipAdapter.GetMember(memberId);

                if (request.IsValidModel())
                {
                    if (member.Exists())
                    {
                        if (member.ConfirmedRegistration())
                        {
                            if (memberId == member.Id)
                            {
                                isValidRequest = true;
                                emailChanged = !string.Equals(request.Email, member.Email, StringComparison.InvariantCultureIgnoreCase);
                            }
                        }
                    }
                }

                if (isValidRequest)
                {
                    var memberProfile = new MemberProfile
                    {
                        MemberId = member.Id,
                        TimeZoneId = request.TimeZoneId,
                        Alias = request.Alias,
                        Gender = request.Gender,
                        BirthDate = request.BirthDate
                    };

                    memberProfile = MembershipAdapter.UpdateProfile(memberProfile);

                    if (emailChanged)
                    {
                        var memberEmailChange = MembershipAdapter.GetMemberEmailChange(member.Id);

                        if (memberEmailChange.Exists())
                        {
                            if (!string.Equals(memberEmailChange.Email, request.Email, StringComparison.InvariantCultureIgnoreCase))
                            {
                                memberEmailChange.Email = request.Email;

                                MembershipAdapter.UpdateEmailChange(memberEmailChange);
                            }
                        }
                        else
                        {
                            memberEmailChange.MemberId = member.Id;
                            memberEmailChange.Email = request.Email;

                            MembershipAdapter.CreateEmailChange(memberEmailChange);
                        }

                        var memberTokens = MembershipAdapter.GetMemberTokens(member.Id, TokenTypes.EmailChange, true);

                        var memberToken = new MemberToken();

                        memberToken.MemberId = member.Id;
                        memberToken.TokenType = TokenTypes.EmailChange;
                        memberToken.RequestDate = DateTime.Now.ToUniversalTime();

                        if (memberTokens.Any())
                        {
                            memberToken.Token = memberTokens.ElementAt(0).Token;
                            memberToken = MembershipAdapter.UpdateToken(memberToken);
                        }
                        else
                        {
                            memberToken.Token = Guid.NewGuid();
                            memberToken = MembershipAdapter.CreateToken(memberToken);
                        }

                        var email = new EmailChangeEmail
                        {
                            DomainName = ConfigHelper.DomainName,
                            DomainBaseUrl = ConfigHelper.DomainBaseUrl,
                            Alias = request.Alias,
                            ConfirmationToken = memberToken.Token
                        };

                        var emailBuilder = new EmailBuilder(EmailReference.HTML.Templates.Main, EmailReference.HTML.Contents.EmailChange);
                        var emailBody = emailBuilder.BuildBody<EmailChangeEmail>(email);
                        var emailResult = EmailHelper.SendEmail(ConfigHelper.NoReplayEmailAddress,
                                                                ConfigHelper.DomainName,
                                                                request.Email,
                                                                member.Profile.Alias,
                                                                email.Subject,
                                                                emailBody,
                                                                true);
                    }

                    response.IsSuccessful = true;
                    response.StatusMessage = "Update profile succeeded";
                }
                else
                {
                    response.IsSuccessful = false;
                    response.StatusMessage = "Update profile was unsuccessful";
                    response.Errors.AddRange(request.GetErrors());
                }
            }
            catch (Exception ex)
            {
                this.Log<ProfileUpdateRequest>(LogCategories.Error, request, ex.Message);

                response.IsSuccessful = false;
                response.StatusMessage = this.StatusMessageForExpection;
                response.Errors.Add(ex.Message);
            }

            return Ok(response);
        }
        public IHttpActionResult ResetPasswordToken(ResetPasswordRequest request)
        {
            var response = new SignInResponse();

            try
            {
                var isValidRequest = false;

                var memberId = request.GetMemberId();
                var member = MembershipAdapter.GetMember(request.Token);

                if (request.IsValidModel())
                {
                    if (!request.PasswordsMatch())
                    {
                        request.AddError("Password", "Passwords do not match");
                    }
                    else
                    {
                        if (member.Exists())
                        {
                            if (memberId == member.Id)
                            {
                                if (member.HasTokens())
                                {
                                    if (member.Tokens.ElementAt(0).IsValid(TokenTypes.PasswordReset))
                                    {
                                        isValidRequest = true;
                                    }
                                }
                            }
                        }
                    }
                }

                if (isValidRequest)
                {
                    var memberPassword = new MemberPassword();
                    memberPassword.MemberId = member.Id;
                    memberPassword.InitializePassword(request.Password);

                    MembershipAdapter.UpdatePassword(memberPassword);

                    var memberToken = new MemberToken
                    {
                        Token = member.Tokens.ElementAt(0).Token,
                        MemberId = member.Id,
                        TokenType = member.Tokens.ElementAt(0).TokenType,
                        ExpirationDate = member.Tokens.ElementAt(0).ExpirationDate,
                        ConfirmedDate = DateTime.Now.ToUniversalTime(),
                        RequestDate = member.Tokens.ElementAt(0).RequestDate
                    };

                    MembershipAdapter.UpdateToken(memberToken);

                    response.MemberId = member.Id.ToString();
                    response.Alias = member.Profile.Alias;
                    response.IsActive = member.IsActive;
                    response.IsAdmin = member.IsAdmin;

                    var email = new ResetPasswordEmail
                    {
                        DomainName = ConfigHelper.DomainName,
                        DomainBaseUrl = ConfigHelper.DomainBaseUrl,
                        Alias = member.Profile.Alias
                    };

                    var emailBuilder = new EmailBuilder(EmailReference.HTML.Templates.Main, EmailReference.HTML.Contents.ResetPassword);
                    var emailBody = emailBuilder.BuildBody<ResetPasswordEmail>(email);
                    var emailResult = EmailHelper.SendEmail(ConfigHelper.NoReplayEmailAddress,
                                                            ConfigHelper.DomainName,
                                                            member.Email,
                                                            member.Profile.Alias,
                                                            email.Subject,
                                                            emailBody,
                                                            true);

                    if (emailResult)
                    {
                        response.IsSuccessful = true;
                        response.StatusMessage = "Reset password succeeded";
                    }
                }
                else
                {
                    response.IsSuccessful = false;
                    response.StatusMessage = "Reset password was unsuccessful";
                    response.Errors.AddRange(request.GetErrors());
                }
            }
            catch (Exception ex)
            {
                request.Password = string.Empty;
                request.PasswordConfirm = string.Empty;

                this.Log<ResetPasswordRequest>(LogCategories.Error, request, ex.Message);

                response.IsSuccessful = false;
                response.StatusMessage = this.StatusMessageForExpection;
                response.Errors.Add(ex.Message);
            }

            return Ok(response);
        }
        public IHttpActionResult Register(RegistrationRequest request)
        {
            var response = new RegistrationResponse();

            try
            {
                var member = MembershipAdapter.GetMember(request.Email);

                if (member.Exists() && member.ConfirmedRegistration())
                {
                    request.AddError("Email", "Email already exists");
                }

                if (request.IsValidModel())
                {
                    if (!request.PasswordsMatch())
                    {
                        request.AddError("Password", "Passwords do not match");
                    }
                }

                if (!request.HasErrors())
                {
                    if (member.IsNewRegistration())
                    {
                        member.Email = request.Email;
                        member.RegistrationDate = DateTime.Now.ToUniversalTime();
                        member.IsActive = true;
                        member.IsAdmin = false;

                        member.Security = new MemberPassword();
                        member.Security.InitializePassword(request.Password);

                        member.Profile = new MemberProfile();
                        member.Profile.Alias = request.Alias;
                        member.Profile.TimeZoneId = ConfigHelper.DefaultTimeZoneId;

                        var registrationToken = new MemberToken();

                        registrationToken.Token = Guid.NewGuid();
                        registrationToken.TokenType = TokenTypes.Registration;
                        registrationToken.RequestDate = member.RegistrationDate;

                        member.Tokens.Add(registrationToken);

                        member = MembershipAdapter.AddMember(member);
                    }
                    else if (member.IsPendingRegistrationConfirmation())
                    {
                        member.Security.InitializePassword(request.Password);
                        member.Profile.Alias = request.Alias;

                        var registrationToken = MembershipAdapter.GetMemberTokens(member.Id, TokenTypes.Registration, true);

                        member.Tokens.Add(registrationToken.ElementAt(0));

                        member = MembershipAdapter.ReRegisterMember(member);
                    }

                    var email = new RegistrationEmail
                    {
                        DomainName = ConfigHelper.DomainName,
                        DomainBaseUrl = ConfigHelper.DomainBaseUrl,
                        Alias = request.Alias,
                        ConfirmationToken = member.Tokens.ElementAt(0).Token
                    };

                    var emailBuilder = new EmailBuilder(EmailReference.HTML.Templates.Main, EmailReference.HTML.Contents.Registration);
                    var emailBody = emailBuilder.BuildBody<RegistrationEmail>(email);
                    var emailResult = EmailHelper.SendEmail(ConfigHelper.NoReplayEmailAddress,
                                                            ConfigHelper.DomainName,
                                                            request.Email,
                                                            request.Alias,
                                                            email.Subject,
                                                            emailBody,
                                                            true);

                    if (emailResult)
                    {
                        response.IsSuccessful = true;
                        response.StatusMessage = "Registration succeeded";
                    }
                }
                else
                {
                    response.Errors.AddRange(request.GetErrors());
                    response.IsSuccessful = false;
                    response.StatusMessage = "Registration was unsuccessful";
                }
            }
            catch (Exception ex)
            {
                request.Password = string.Empty;
                request.PasswordConfirm = string.Empty;

                this.Log<RegistrationRequest>(LogCategories.Error, request, ex.Message);

                response.IsSuccessful = false;
                response.StatusMessage = this.StatusMessageForExpection;
                response.Errors.Add(ex.Message);
            }

            return Ok(response);
        }
        public IHttpActionResult ForgotPassword(ForgotPasswordRequest request)
        {
            var response = new ForgotPasswordResponse();

            try
            {
                var isValidRequest = false;

                var member = MembershipAdapter.GetMember(request.Email);

                if (request.IsValidModel())
                {
                    if (member.Exists())
                    {
                        if (member.ConfirmedRegistration())
                        {
                            isValidRequest = true;
                        }
                    }
                }

                if (isValidRequest)
                {
                    MemberToken memberToken = new MemberToken();

                    memberToken.MemberId = member.Id;
                    memberToken.TokenType = TokenTypes.PasswordReset;
                    memberToken.RequestDate = DateTime.Now.ToUniversalTime();
                    memberToken.ExpirationDate = memberToken.RequestDate.AddHours(ConfigHelper.PasswordResetExpiration);

                    var memberTokens = MembershipAdapter.GetMemberTokens(member.Id, TokenTypes.PasswordReset, true);

                    if (!memberTokens.Any())
                    {
                        memberToken.Token = Guid.NewGuid();

                        memberToken = MembershipAdapter.CreateToken(memberToken);
                    }
                    else
                    {
                        memberToken.Token = memberTokens.ElementAt(0).Token;

                        memberToken = MembershipAdapter.UpdateToken(memberToken);
                    }

                    var email = new ForgotPasswordEmail
                    {
                        DomainName = ConfigHelper.DomainName,
                        DomainBaseUrl = ConfigHelper.DomainBaseUrl,
                        Alias = member.Profile.Alias,
                        Token = memberToken.Token
                    };

                    var emailBuilder = new EmailBuilder(EmailReference.HTML.Templates.Main, EmailReference.HTML.Contents.ForgotPassword);
                    var emailBody = emailBuilder.BuildBody<ForgotPasswordEmail>(email);
                    var emailResult = EmailHelper.SendEmail(ConfigHelper.NoReplayEmailAddress,
                                                            ConfigHelper.DomainName,
                                                            member.Email,
                                                            member.Profile.Alias,
                                                            email.Subject,
                                                            emailBody,
                                                            true);
                    if (emailResult)
                    {
                        response.IsSuccessful = true;
                        response.StatusMessage = "Forgot password succeeded";
                    }

                }
                else
                {
                    response.IsSuccessful = false;
                    response.StatusMessage = "Forgot password was unsuccessful";
                    response.Errors.AddRange(request.GetErrors());
                }
            }
            catch (Exception ex)
            {
                this.Log<ForgotPasswordRequest>(LogCategories.Error, request, ex.Message);

                response.IsSuccessful = false;
                response.StatusMessage = this.StatusMessageForExpection;
                response.Errors.Add(ex.Message);
            }

            return Ok(response);
        }
        public IHttpActionResult ConfirmEmailChange(Guid token)
        {
            var response = new EmailChangeConfirmationResponse();

            try
            {
                var isValidToken = false;

                var member = MembershipAdapter.GetMember(token);

                if (member.Exists())
                {
                    if (member.ConfirmedRegistration())
                    {
                        if (member.HasTokens())
                        {
                            if (member.Tokens.ElementAt(0).IsValid(TokenTypes.EmailChange))
                            {
                                member.EmailChange = MembershipAdapter.GetMemberEmailChange(member.Id);

                                if (member.EmailChange.Exists())
                                {
                                    isValidToken = true;
                                }
                            }
                        }
                    }
                }

                if (isValidToken)
                {
                    member.EmailChange = MembershipAdapter.UpdateEmail(member.EmailChange);

                    var memberToken = new MemberToken
                    {
                        Token = member.Tokens.ElementAt(0).Token,
                        MemberId = member.Id,
                        TokenType = TokenTypes.EmailChange,
                        RequestDate = member.Tokens.ElementAt(0).RequestDate,
                        ConfirmedDate = DateTime.Now.ToUniversalTime()
                    };

                    memberToken = MembershipAdapter.UpdateToken(memberToken);

                    var email = new EmailChangeConfirmationEmail
                    {
                        DomainName = ConfigHelper.DomainName,
                        DomainBaseUrl = ConfigHelper.DomainBaseUrl,
                        Alias = member.Profile.Alias
                    };

                    var emailBuilder = new EmailBuilder(EmailReference.HTML.Templates.Main, EmailReference.HTML.Contents.EmailChangeConfirmation);
                    var emailBody = emailBuilder.BuildBody<EmailChangeConfirmationEmail>(email);
                    var emailResult = EmailHelper.SendEmail(ConfigHelper.NoReplayEmailAddress,
                                                            ConfigHelper.DomainName,
                                                            member.EmailChange.Email,
                                                            member.Profile.Alias,
                                                            email.Subject,
                                                            emailBody,
                                                            true);

                    if (emailResult)
                    {
                        response.IsSuccessful = true;
                        response.StatusMessage = "Email change succeeded";
                    }
                }
                else
                {
                    response.IsSuccessful = true;
                    response.StatusMessage = "Email change was unsuccessful";
                }
            }
            catch (Exception ex)
            {
                this.Log(LogCategories.Error, token.ToString(), ex.Message);

                response.IsSuccessful = false;
                response.StatusMessage = this.StatusMessageForExpection;
                response.Errors.Add(ex.Message);
            }

            return Ok(response);
        }
        public MemberToken UpdateToken(MemberToken memberToken)
        {
            using (context = new DomainContext())
            {
                context.Configuration.LazyLoadingEnabled = false;

                context.MemberTokens.Attach(memberToken);
                context.Entry<MemberToken>(memberToken).State = EntityState.Modified;

                context.SaveChanges();
            }

            return memberToken;
        }