public EmailUser AddUser(EmailUser user)
        {
            if (!IsValidUserName(user.Name))
            {
                throw new InvalidOperationException(String.Format("{0} is not a valid user name.", user.Name));
            }

            if (String.IsNullOrEmpty(user.Password))
            {
                ThrowPasswordIsRequired();
            }

            EnsureUserNameIsAvailable(user.Name);

            user.Status = 1;
            user.Salt = _crypto.CreateSalt();
            user.LastActivity = DateTime.UtcNow;

            ValidatePassword(user.Password);
            user.Password = user.Password.ToSha256(user.Salt);

            _session.Store(user);
            _session.SaveChanges();

            return user;
        }
        public void ChangeUserName(EmailUser user, string newUserName)
        {
            if (!IsValidUserName(newUserName))
            {
                throw new InvalidOperationException(String.Format("{0} is not a valid user name.", newUserName));
            }

            if (user.Name.Equals(newUserName, StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("That's already your username...");
            }

            EnsureUserNameIsAvailable(newUserName);

            // Update the user name
            user.Name = newUserName;
        }
 public UserModule(ICryptoService crypto)
     : base("user")
 {
     //Get a list of all the users in the same organization as you.
     Get["/"] = _ =>
     {
         if (!IsAuthenticated)
         {
             return HttpStatusCode.Unauthorized;
         }
         var user =
             DocumentSession.Load<EmailUser>(Principal.GetUserId());
         var users =
             DocumentSession.Query<EmailUser>()
                 .Where(u => u.Organization.Id == user.Organization.Id)
                 .Select(c => new UserViewModel {Name = c.Name, Organization = c.Organization.Name}).ToList();
         return Response.AsJson(users);
     };
     Post["/"] = _ =>
     {
         //If User is authenticated and is the org admin.
         if (IsAuthenticated && Principal.HasClaim(EmailRClaimTypes.Admin))
         {
             return HttpStatusCode.Unauthorized;
         }
         var user =
             DocumentSession.Load<EmailUser>(Principal.GetUserId());
         var createUser = this.Bind<CreateUserViewModel>();
         var salt = crypto.CreateSalt();
         var newUser = new EmailUser
         {
             Email = createUser.Email,
             FriendlyName = createUser.FriendlyName,
             //Id = Guid.NewGuid(),
             Password = createUser.Password.ToSha256(salt),
             Salt = salt,
             LoginType = "Default",
             Organization = user.Organization,
             Name = createUser.UserName,
             IsAdmin = false
         };
         DocumentSession.Store(newUser);
         return HttpStatusCode.OK;
     };
 }
        public void ChangeUserPassword(EmailUser user, string oldPassword, string newPassword)
        {
            if (user.Password != oldPassword.ToSha256(user.Salt))
            {
                throw new InvalidOperationException("Passwords don't match.");
            }

            ValidatePassword(newPassword);

            EnsureSaltedPassword(user, newPassword);
        }
 private void EnsureSaltedPassword(EmailUser user, string password)
 {
     if (String.IsNullOrEmpty(user.Salt))
     {
         user.Salt = _crypto.CreateSalt();
     }
     user.Password = password.ToSha256(user.Salt);
 }
        private EmailUser AddUser(string userName, string providerName, string identity, string email)
        {
            if (!IsValidUserName(userName))
            {
                throw new InvalidOperationException(String.Format("{0} is not a valid user name.", userName));
            }

            EnsureProviderAndIdentityAvailable(providerName, identity);

            // This method is used in the auth workflow. If the username is taken it will add a number
            // to the user name.
            if (UserExists(userName))
            {
                throw new InvalidOperationException(String.Format("{0} is already in use.", userName));
            }

            var user = new EmailUser
            {
                Name = userName,
                Status = 1,
                LastActivity = DateTime.UtcNow
            };

            var emailUserIdentity = new EmailUserIdentity
            {
                Key = Guid.NewGuid(),
                User = user,
                Email = email,
                Identity = identity,
                ProviderName = providerName
            };
            _session.Store(user);
            _session.Store(emailUserIdentity);
            _session.SaveChanges();

            return user;
        }
 public bool TryAuthenticateUser(string userName, string password, out EmailUser user)
 {
     user = _session.Query<EmailUser>().FirstOrDefault(x => x.Name == userName);
     if (user != null && user.Password == password.ToSha256(user.Salt))
         return true;
     return false;
 }
 public void SetUserPassword(EmailUser user, string password)
 {
     ValidatePassword(password);
     user.Password = password.ToSha256(user.Salt);
 }
        public void ResetUserPassword(EmailUser user, string newPassword)
        {
            user.RequestPasswordResetId = null;
            user.RequestPasswordResetValidThrough = null;

            ValidatePassword(newPassword);

            EnsureSaltedPassword(user, newPassword);
        }
 public void RequestResetPassword(EmailUser user, int requestValidThroughInHours)
 {
     user.RequestPasswordResetId = HttpServerUtility.UrlTokenEncode(_crypto.CreateToken(user.Name));
     user.RequestPasswordResetValidThrough = DateTimeOffset.UtcNow.AddHours(requestValidThroughInHours);
 }
        public void LinkIdentity(EmailUser user, ClaimsPrincipal claimsPrincipal)
        {
            var identity = claimsPrincipal.GetClaimValue(ClaimTypes.NameIdentifier);
            var email = claimsPrincipal.GetClaimValue(ClaimTypes.Email);
            var providerName = claimsPrincipal.GetIdentityProvider();

            // Link this new identity
            user.Identities.Add(new EmailUserIdentity
            {
                Email = email,
                Identity = identity,
                ProviderName = providerName
            });
        }
        public LoginModule(IMembershipService membershipService,
                               IUserAuthenticator authenticator)
        {
            //Get the login page.
            Get["/login"] = _ =>
            {
                string returnUrl = Request.Query.returnUrl;
                if (IsAuthenticated)
                {
                    return Response.AsRedirect(returnUrl);
                }
                var model = new LoginViewModel
                {
                    ReturnUrl = returnUrl
                };

                Model.LoginModel = model;
                return View["login", Model];
            };

            Get["/logout"] = parameters =>
            {
                return View["login"];
            };

            //Login.
            Post["/login"] = parameters =>
            {
                var model = this.Bind<LoginViewModel>();

                //If user is already authenticated redirect them to the returnUrl.
                if (IsAuthenticated)
                    return Response.AsRedirect(model.ReturnUrl);

                var result = this.Validate(model);

                if (!result.IsValid)
                {
                    SaveErrors(result.Errors);
                    Model.LoginModel = model;
                    return View["login", Model];
                }

                IList<Claim> claims;
                if (authenticator.TryAuthenticateUser(model.Username, model.Password, out claims))
                {
                    return this.SignIn(claims, model.ReturnUrl);
                }
                Page.ValidationSummary = "Your username or password was incorrect";
                Model.LoginModel = model;
                return View["login", Model];
            };

            Get["/register"] = parameters =>
            {
                var registerModel = new RegisterViewModel();
                var returnUrl = Request.Query.returnUrl;
                registerModel.ReturnUrl = returnUrl;
                Model.RegisterModel = registerModel;
                return View["register", Model];
            };
            //Register a new user.
            Post["/register"] = _ =>
            {
                var registerModel = this.Bind<RegisterViewModel>();
                Model.RegisterModel = registerModel;
                var result = this.Validate(registerModel);
                if (!result.IsValid)
                {
                    SaveErrors(result.Errors);
                    return View["register", Model];
                }
                var user = new EmailUser
                {
                    Email = registerModel.Email,
                    FriendlyName = registerModel.Name,
                    Id = registerModel.UserName,
                    IsAdmin = false,
                    LoginType = "Default",
                    Name = registerModel.UserName,
                    Password = registerModel.Password
                };
                user = membershipService.AddUser(user);
                return this.SignIn(user, registerModel.ReturnUrl);
            };
        }
        private static void AddClaim(CookieResponseSignInContext context, EmailUser user)
        {
            // Add the jabbr id claim
            context.Identity.AddClaim(new Claim(EmailRClaimTypes.Identifier, user.Id.ToString()));

            // Add the admin claim if the user is an Administrator
            if (user.IsAdmin)
            {
                context.Identity.AddClaim(new Claim(EmailRClaimTypes.Admin, "true"));
            }

            EnsurePersistentCookie(context);
        }