Example #1
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="userAuthenticator">The user authenticator.</param>
        /// <param name="method">The authentication method.</param>
        /// <param name="parameter">The authentication parameter.</param>
        public AuthCommand(IUserAuthenticator userAuthenticator, AuthenticationMethod method, string parameter)
        {
            _userAuthenticator = userAuthenticator;

            Method    = method;
            Parameter = parameter;
        }
 public AuthenticationService(ICurrentSDKUser currentSdkUser, IFormsAuthenticationService formsAuthentication, IUserAuthenticator agentAuthenticator, IClarifySessionCache sessionCache, IPrincipalFactory principalFactory)
 {
     _currentSdkUser = currentSdkUser;
     _formsAuthentication = formsAuthentication;
     _agentAuthenticator = agentAuthenticator;
     _sessionCache = sessionCache;
     _principalFactory = principalFactory;
 }
 public AuthenticationService(ICurrentSDKUser currentSdkUser, IFormsAuthenticationService formsAuthentication, IUserAuthenticator agentAuthenticator, IPrincipalFactory principalFactory, ILogger logger)
 {
     _currentSdkUser = currentSdkUser;
     _formsAuthentication = formsAuthentication;
     _agentAuthenticator = agentAuthenticator;
     _principalFactory = principalFactory;
     _logger = logger;
 }
Example #4
0
 public AuthenticationService(ICurrentSDKUser currentSdkUser, IFormsAuthenticationService formsAuthentication, IUserAuthenticator agentAuthenticator, IClarifySessionCache sessionCache, IPrincipalFactory principalFactory)
 {
     _currentSdkUser      = currentSdkUser;
     _formsAuthentication = formsAuthentication;
     _agentAuthenticator  = agentAuthenticator;
     _sessionCache        = sessionCache;
     _principalFactory    = principalFactory;
 }
Example #5
0
 public BuildController(ILogger logger, IPartitionedKeyValueDictionary data, IAppBlobStorage blobService, IUserAuthenticator ua, IAppSearchService ss)
 {
     this._logger      = logger;
     this._data        = data;
     this._blobService = blobService;
     this._ua          = ua;
     this._search      = ss;
 }
Example #6
0
 public RegisterUserHandler(UserService userService,
                            RegistrationEmailSender emailSender,
                            IUserAuthenticator authenticator)
 {
     _userService   = userService;
     _emailSender   = emailSender;
     _authenticator = authenticator;
 }
 public UserController(ISessionManager sessionManager, IUserAuthenticator authenticator,
                       IUserRepository userRepository, IAuthorisation authoriser)
 {
     this.UserRepository = userRepository;
     this.SessionManager = sessionManager;
     this.Authenticator  = authenticator;
     this.Authorisation  = authoriser;
 }
Example #8
0
 private Core( )
 {
     _IDataContext                = new DataContext( );
     _IDiagnosticsHandler         = new DiagnosticsHandler( );
     _ICP4DatabaseServiceProvider = new CP4DatabaseServiceProvider( );
     _IUserAuthenticator          = new DummyAuthManager( );
     _LazyINavigationHandler      = new Lazy <INavigationHandler>(() => new NavigationHandler((( INavigationServiceProvider )App.Current.MainWindow).NavigationService));
 }
        /// <summary>
        /// Used to set the user authenticator. NetWorker must not already be connected.
        /// </summary>
        public void SetUserAuthenticator(IUserAuthenticator authenticator)
        {
            if (IsConnected)
            {
                throw new BaseNetworkException("The NetWorker is already connected");
            }

            this.authenticator = authenticator;
        }
 public AuthenticationService(ICurrentSDKUser currentSdkUser,
     IFormsAuthenticationService formsAuthentication,
     IUserAuthenticator agentAuthenticator,
     IUserImpersonationService impersonationService,
     ILogger logger)
 {
     _currentSdkUser = currentSdkUser;
     _formsAuthentication = formsAuthentication;
     _agentAuthenticator = agentAuthenticator;
     _impersonationService = impersonationService;
     _logger = logger;
 }
        public async Task Invoke_returns_200_with_token_if_match([Frozen] IUserAuthenticator authenticator, [Frozen] IUserExtractor extractor, JwtMiddleware sut, [Frozen] IServiceProvider serviceProvider, HttpContext context, JwtOptions options, IActionResultExecutor <ObjectResult> executor, User user, ClaimsIdentity identity)
        {
            Mock.Get(extractor).Setup(p => p.TryExtractUser(It.IsAny <HttpContext>(), out user)).Returns(true);

            Mock.Get(authenticator).Setup(p => p.TryAuthenticateUserAsync(It.IsAny <User>(), out identity)).ReturnsAsync(true);

            Mock.Get(serviceProvider).Setup(p => p.GetService(typeof(IActionResultExecutor <ObjectResult>))).Returns(executor);

            await sut.Invoke(context, options);

            Mock.Get(executor).Verify(p => p.ExecuteAsync(It.IsAny <ActionContext>(), It.Is <ObjectResult>(or => or.StatusCode == 200 && or.Value is TokenModel)));
        }
 public AuthenticationService(ICurrentSDKUser currentSdkUser,
                              IFormsAuthenticationService formsAuthentication,
                              IUserAuthenticator agentAuthenticator,
                              IUserImpersonationService impersonationService,
                              ILogger logger)
 {
     _currentSdkUser       = currentSdkUser;
     _formsAuthentication  = formsAuthentication;
     _agentAuthenticator   = agentAuthenticator;
     _impersonationService = impersonationService;
     _logger = logger;
 }
Example #13
0
        public async Task <Token> LogIn(IUserAuthenticator authenticator)
        {
            await _authClient.AuthenticationRequest(HttpMethod.Get);

            if (User.Username == null && User.Password == null)
            {
                var credentials = await authenticator.OnLogInChallenge();

                User.Username = credentials.Item1;
                User.Password = credentials.Item2;
            }

            // User requested to cancel login process
            if (User.Username == null && User.Password == null)
            {
                User.Username = null;
                User.Password = null;
                return(null);
            }

            if (await _authClient.LogInRequest(User) == null)
            {
                User.Username = null;
                User.Password = null;
                return(null);
            }

            if (await authenticator.OnAppAuthorizeChallenge())
            {
                await _authClient.AuthenticationRequest(HttpMethod.Post);

                UpdateAuthenticationInfo(_authClient.ObtainedToken);
            }
            else
            {
                User.Username = null;
                User.Password = null;
                return(null);
            }

            authenticator.OnLogIn(User.Username, User.Password);
            return(User.AccessToken);
        }
Example #14
0
        public HomeModule(ApplicationSettings settings,
                          IMembershipService membershipService,
                          IUserAuthenticator authenticator,
                          IRepository <ChatUser> repository,
                          IChatConfiguration configuration
                          )
        {
            Get["/"] = _ =>
            {
                if (IsAuthenticated)
                {
                    var viewModel = new SettingsViewModel
                    {
                        GoogleAnalytics         = settings.GoogleAnalytics,
                        AppInsights             = settings.AppInsights,
                        Sha                     = configuration.DeploymentSha,
                        Branch                  = configuration.DeploymentBranch,
                        Time                    = configuration.DeploymentTime,
                        DebugMode               = (bool)Context.Items["_debugMode"],
                        Version                 = Constants.ChatVersion,
                        IsAdmin                 = Principal.HasClaim(ChatClaimTypes.Admin),
                        ClientLanguageResources = BuildClientResources(),
                        MaxMessageLength        = settings.MaxMessageLength,
                        AllowRoomCreation       = settings.AllowRoomCreation || Principal.HasClaim(ChatClaimTypes.Admin)
                    };

                    return(View["index", viewModel]);
                }

                if (Principal != null && Principal.HasPartialIdentity())
                {
                    // If the user is partially authenticated then take them to the register page
                    return(Response.AsRedirect("~/account/register"));
                }

                return(HttpStatusCode.Unauthorized);
            };
        }
Example #15
0
        public AccountModule(ApplicationSettings applicationSettings,
                             IMembershipService membershipService,
                             IJabbrRepository repository,
                             IAuthenticationService authService,
                             IChatNotificationService notificationService,
                             IUserAuthenticator authenticator)
            : base("/account")
        {
            Get["/"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return(HttpStatusCode.Forbidden);
                }

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                return(GetProfileView(authService, user));
            };

            Get["/login"] = _ =>
            {
                if (IsAuthenticated)
                {
                    return(Response.AsRedirect("~/"));
                }

                return(View["login", GetLoginViewModel(applicationSettings, repository, authService)]);
            };

            Post["/login"] = param =>
            {
                if (IsAuthenticated)
                {
                    return(Response.AsRedirect("~/"));
                }

                string username = Request.Form.username;
                string password = Request.Form.password;

                if (String.IsNullOrEmpty(username))
                {
                    this.AddValidationError("username", "Name is required");
                }

                if (String.IsNullOrEmpty(password))
                {
                    this.AddValidationError("password", "Password is required");
                }

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        IList <Claim> claims;
                        if (authenticator.TryAuthenticateUser(username, password, out claims))
                        {
                            return(this.SignIn(claims));
                        }
                    }
                }
                catch
                {
                    // Swallow the exception
                }

                this.AddValidationError("_FORM", "Login failed. Check your username/password.");

                return(View["login", GetLoginViewModel(applicationSettings, repository, authService)]);
            };

            Post["/logout"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return(HttpStatusCode.Forbidden);
                }

                var response = Response.AsJson(new { success = true });

                this.SignOut();

                return(response);
            };

            Get["/register"] = _ =>
            {
                if (IsAuthenticated)
                {
                    return(Response.AsRedirect("~/"));
                }

                bool requirePassword = !Principal.Identity.IsAuthenticated;

                if (requirePassword &&
                    !applicationSettings.AllowUserRegistration)
                {
                    return(HttpStatusCode.NotFound);
                }

                ViewBag.requirePassword = requirePassword;

                return(View["register"]);
            };

            Post["/create"] = _ =>
            {
                bool requirePassword = !Principal.Identity.IsAuthenticated;

                if (requirePassword &&
                    !applicationSettings.AllowUserRegistration)
                {
                    return(HttpStatusCode.NotFound);
                }

                if (IsAuthenticated)
                {
                    return(Response.AsRedirect("~/"));
                }

                ViewBag.requirePassword = requirePassword;

                string username        = Request.Form.username;
                string email           = Request.Form.email;
                string password        = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                if (String.IsNullOrEmpty(username))
                {
                    this.AddValidationError("username", "Name is required");
                }

                if (String.IsNullOrEmpty(email))
                {
                    this.AddValidationError("email", "Email is required");
                }

                try
                {
                    if (requirePassword)
                    {
                        ValidatePassword(password, confirmPassword);
                    }

                    if (ModelValidationResult.IsValid)
                    {
                        if (requirePassword)
                        {
                            ChatUser user = membershipService.AddUser(username, email, password);

                            return(this.SignIn(user));
                        }
                        else
                        {
                            // Add the required claims to this identity
                            var identity = Principal.Identity as ClaimsIdentity;

                            if (!Principal.HasClaim(ClaimTypes.Name))
                            {
                                identity.AddClaim(new Claim(ClaimTypes.Name, username));
                            }

                            if (!Principal.HasClaim(ClaimTypes.Email))
                            {
                                identity.AddClaim(new Claim(ClaimTypes.Email, email));
                            }

                            return(this.SignIn(Principal.Claims));
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                return(View["register"]);
            };

            Post["/unlink"] = param =>
            {
                if (!IsAuthenticated)
                {
                    return(HttpStatusCode.Forbidden);
                }

                string   provider = Request.Form.provider;
                ChatUser user     = repository.GetUserById(Principal.GetUserId());

                if (user.Identities.Count == 1 && !user.HasUserNameAndPasswordCredentials())
                {
                    Request.AddAlertMessage("error", "You cannot unlink this account because you would lose your ability to login.");
                    return(Response.AsRedirect("~/account/#identityProviders"));
                }

                var identity = user.Identities.FirstOrDefault(i => i.ProviderName == provider);

                if (identity != null)
                {
                    repository.Remove(identity);

                    Request.AddAlertMessage("success", String.Format("Successfully unlinked {0} account.", provider));
                    return(Response.AsRedirect("~/account/#identityProviders"));
                }

                return(HttpStatusCode.BadRequest);
            };

            Post["/newpassword"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return(HttpStatusCode.Forbidden);
                }

                string password        = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                ValidatePassword(password, confirmPassword);

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.SetUserPassword(user, password);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    Request.AddAlertMessage("success", "Successfully added a password.");
                    return(Response.AsRedirect("~/account/#changePassword"));
                }

                return(GetProfileView(authService, user));
            };

            Post["/changepassword"] = _ =>
            {
                if (!applicationSettings.AllowUserRegistration)
                {
                    return(HttpStatusCode.NotFound);
                }

                if (!IsAuthenticated)
                {
                    return(HttpStatusCode.Forbidden);
                }

                string oldPassword     = Request.Form.oldPassword;
                string password        = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                if (String.IsNullOrEmpty(oldPassword))
                {
                    this.AddValidationError("oldPassword", "Old password is required");
                }

                ValidatePassword(password, confirmPassword);

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.ChangeUserPassword(user, oldPassword, password);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    Request.AddAlertMessage("success", "Successfully changed your password.");
                    return(Response.AsRedirect("~/account/#changePassword"));
                }

                return(GetProfileView(authService, user));
            };

            Post["/changeusername"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return(HttpStatusCode.Forbidden);
                }

                string username        = Request.Form.username;
                string confirmUsername = Request.Form.confirmUsername;

                ValidateUsername(username, confirmUsername);

                ChatUser user        = repository.GetUserById(Principal.GetUserId());
                string   oldUsername = user.Name;

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.ChangeUserName(user, username);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    notificationService.OnUserNameChanged(user, oldUsername, username);

                    Request.AddAlertMessage("success", "Successfully changed your username.");
                    return(Response.AsRedirect("~/account/#changeUsername"));
                }

                return(GetProfileView(authService, user));
            };
        }
Example #16
0
 public AuthenticationController(IAntiforgery antiForgery, IUserAuthenticator authenticator)
 {
     this.antiForgery   = antiForgery;
     this.authenticator = authenticator;
 }
 public ContactAuthenticationService(IFormsAuthenticationService formsAuthentication, ContactAuthenticator agentAuthenticator, IClarifySessionCache sessionCache)
 {
     _formsAuthentication = formsAuthentication;
     _agentAuthenticator  = agentAuthenticator;
     _sessionCache        = sessionCache;
 }
Example #18
0
 public void LogOut(IUserAuthenticator authenticator)
 {
     authenticator.OnLogOut(User.Username);
     RemoveCookie("reddit_session");
     User = new User();
 }
Example #19
0
 public HomeController(IOptions <SiteSettings> s, ILogger logger, IUserAuthenticator ua)
 {
     ss  = s.Value;
     _ua = ua;
 }
 public ContactAuthenticationService(IFormsAuthenticationService formsAuthentication, ContactAuthenticator agentAuthenticator, IAuthenticationSignOutService signOutService)
 {
     _formsAuthentication = formsAuthentication;
     _agentAuthenticator = agentAuthenticator;
     _signOutService = signOutService;
 }
Example #21
0
        /// <summary>
        /// Sets the User Authenticator.
        /// </summary>
        /// <param name="userAuthenticator">The user authenticator.</param>
        /// <returns>A OptionsBuilder to continue building on.</returns>
        public OptionsBuilder UserAuthenticator(IUserAuthenticator userAuthenticator)
        {
            _options.UserAuthenticator = userAuthenticator;

            return this;
        }
Example #22
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="userAuthenticator">The user authenticator.</param>
 /// <param name="method">The authentication method.</param>
 /// <param name="parameter">The authentication parameter.</param>
 public AuthCommand(IUserAuthenticator userAuthenticator, AuthenticationMethod method, string parameter)
 {
     _userAuthenticator = userAuthenticator;
     _method = method;
     _parameter = parameter;
 }
 public ProxyService(IUserFinder userFinder, IUserAuthenticator userAuthenticator)
 {
     this.userFinder = userFinder;
     this.userAuthenticator = userAuthenticator;
 }
Example #24
0
 private Core( )
 {
     _IUserDataSerializer    = new DataContext( );
     _IUserAuthenticator     = new AuthenticationManager( );
     _LazyINavigationHandler = new Lazy <INavigationHandler>(() => new NavigationHandler((( INavigationServiceProvider )App.Current.MainWindow).NavigationService));
 }
 /// <summary>
 /// Add an instance of the user authenticator.
 /// </summary>
 /// <param name="userAuthenticator">The user authenticator.</param>
 public void Add(IUserAuthenticator userAuthenticator)
 {
     _userAuthenticatorFactory = new DelegatingUserAuthenticatorFactory(context => userAuthenticator);
 }
        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);
            };
        }
 public UserAuthenticatorFactory(IUserAuthenticator authenticator)
 {
     _authenticator = authenticator;
 }
 public TokenAuthenticationApi(IAuthenticationTokenRepository repository, IUserAuthenticator authenticator)
 {
     _repository = repository;
     _authenticator = authenticator;
 }
Example #29
0
        public AccountModule(ApplicationSettings applicationSettings,
                             IMembershipService membershipService,
                             IJabbrRepository repository,
                             IAuthenticationService authService,
                             IChatNotificationService notificationService,
                             IUserAuthenticator authenticator,
                             IEmailService emailService)
            : base("/account")
        {
            Get["/"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return(HttpStatusCode.Forbidden);
                }

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                return(GetProfileView(authService, user));
            };

            Get["/login"] = _ =>
            {
                if (IsAuthenticated)
                {
                    return(this.AsRedirectQueryStringOrDefault("~/"));
                }

                return(View["login", GetLoginViewModel(applicationSettings, repository, authService)]);
            };

            Post["/login"] = param =>
            {
                if (IsAuthenticated)
                {
                    return(this.AsRedirectQueryStringOrDefault("~/"));
                }

                string username = Request.Form.username;
                string password = Request.Form.password;

                if (String.IsNullOrEmpty(username))
                {
                    this.AddValidationError("username", LanguageResources.Authentication_NameRequired);
                }

                if (String.IsNullOrEmpty(password))
                {
                    this.AddValidationError("password", LanguageResources.Authentication_PassRequired);
                }

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        IList <Claim> claims;
                        if (authenticator.TryAuthenticateUser(username, password, out claims))
                        {
                            return(this.SignIn(claims));
                        }
                    }
                }
                catch
                {
                    // Swallow the exception
                }

                this.AddValidationError("_FORM", LanguageResources.Authentication_GenericFailure);

                return(View["login", GetLoginViewModel(applicationSettings, repository, authService)]);
            };

            Post["/logout"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return(HttpStatusCode.Forbidden);
                }

                var response = Response.AsJson(new { success = true });

                this.SignOut();

                return(response);
            };

            Get["/register"] = _ =>
            {
                if (IsAuthenticated)
                {
                    return(this.AsRedirectQueryStringOrDefault("~/"));
                }

                bool requirePassword = !Principal.Identity.IsAuthenticated;

                if (requirePassword &&
                    !applicationSettings.AllowUserRegistration)
                {
                    return(HttpStatusCode.NotFound);
                }

                ViewBag.requirePassword = requirePassword;

                return(View["register"]);
            };

            Post["/create"] = _ =>
            {
                bool requirePassword = !Principal.Identity.IsAuthenticated;

                if (requirePassword &&
                    !applicationSettings.AllowUserRegistration)
                {
                    return(HttpStatusCode.NotFound);
                }

                if (IsAuthenticated)
                {
                    return(this.AsRedirectQueryStringOrDefault("~/"));
                }

                ViewBag.requirePassword = requirePassword;

                string username        = Request.Form.username;
                string email           = Request.Form.email;
                string password        = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                if (String.IsNullOrEmpty(username))
                {
                    this.AddValidationError("username", LanguageResources.Authentication_NameRequired);
                }

                if (String.IsNullOrEmpty(email))
                {
                    this.AddValidationError("email", LanguageResources.Authentication_EmailRequired);
                }

                try
                {
                    if (requirePassword)
                    {
                        ValidatePassword(password, confirmPassword);
                    }

                    if (ModelValidationResult.IsValid)
                    {
                        if (requirePassword)
                        {
                            ChatUser user = membershipService.AddUser(username, email, password);

                            return(this.SignIn(user));
                        }
                        else
                        {
                            // Add the required claims to this identity
                            var identity = Principal.Identity as ClaimsIdentity;

                            if (!Principal.HasClaim(ClaimTypes.Name))
                            {
                                identity.AddClaim(new Claim(ClaimTypes.Name, username));
                            }

                            if (!Principal.HasClaim(ClaimTypes.Email))
                            {
                                identity.AddClaim(new Claim(ClaimTypes.Email, email));
                            }

                            return(this.SignIn(Principal.Claims));
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                return(View["register"]);
            };

            Post["/unlink"] = param =>
            {
                if (!IsAuthenticated)
                {
                    return(HttpStatusCode.Forbidden);
                }

                string   provider = Request.Form.provider;
                ChatUser user     = repository.GetUserById(Principal.GetUserId());

                if (user.Identities.Count == 1 && !user.HasUserNameAndPasswordCredentials())
                {
                    Request.AddAlertMessage("error", LanguageResources.Account_UnlinkRequiresMultipleIdentities);
                    return(Response.AsRedirect("~/account/#identityProviders"));
                }

                var identity = user.Identities.FirstOrDefault(i => i.ProviderName == provider);

                if (identity != null)
                {
                    repository.Remove(identity);

                    Request.AddAlertMessage("success", String.Format(LanguageResources.Account_UnlinkCompleted, provider));
                    return(Response.AsRedirect("~/account/#identityProviders"));
                }

                return(HttpStatusCode.BadRequest);
            };

            Post["/newpassword"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return(HttpStatusCode.Forbidden);
                }

                string password        = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                ValidatePassword(password, confirmPassword);

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.SetUserPassword(user, password);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    Request.AddAlertMessage("success", LanguageResources.Authentication_PassAddSuccess);
                    return(Response.AsRedirect("~/account/#changePassword"));
                }

                return(GetProfileView(authService, user));
            };

            Post["/changepassword"] = _ =>
            {
                if (!applicationSettings.AllowUserRegistration)
                {
                    return(HttpStatusCode.NotFound);
                }

                if (!IsAuthenticated)
                {
                    return(HttpStatusCode.Forbidden);
                }

                string oldPassword     = Request.Form.oldPassword;
                string password        = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                if (String.IsNullOrEmpty(oldPassword))
                {
                    this.AddValidationError("oldPassword", LanguageResources.Authentication_OldPasswordRequired);
                }

                ValidatePassword(password, confirmPassword);

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.ChangeUserPassword(user, oldPassword, password);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    Request.AddAlertMessage("success", LanguageResources.Authentication_PassChangeSuccess);
                    return(Response.AsRedirect("~/account/#changePassword"));
                }

                return(GetProfileView(authService, user));
            };

            Post["/changeusername"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return(HttpStatusCode.Forbidden);
                }

                string username        = Request.Form.username;
                string confirmUsername = Request.Form.confirmUsername;

                ValidateUsername(username, confirmUsername);

                ChatUser user        = repository.GetUserById(Principal.GetUserId());
                string   oldUsername = user.Name;

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.ChangeUserName(user, username);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    notificationService.OnUserNameChanged(user, oldUsername, username);

                    Request.AddAlertMessage("success", LanguageResources.Authentication_NameChangeCompleted);
                    return(Response.AsRedirect("~/account/#changeUsername"));
                }

                return(GetProfileView(authService, user));
            };

            Get["/requestresetpassword"] = _ =>
            {
                if (IsAuthenticated)
                {
                    return(Response.AsRedirect("~/account/#changePassword"));
                }

                if (!Principal.Identity.IsAuthenticated &&
                    !applicationSettings.AllowUserResetPassword ||
                    string.IsNullOrWhiteSpace(applicationSettings.EmailSender))
                {
                    return(HttpStatusCode.NotFound);
                }

                return(View["requestresetpassword"]);
            };

            Post["/requestresetpassword"] = _ =>
            {
                if (IsAuthenticated)
                {
                    return(Response.AsRedirect("~/account/#changePassword"));
                }

                if (!Principal.Identity.IsAuthenticated &&
                    !applicationSettings.AllowUserResetPassword ||
                    string.IsNullOrWhiteSpace(applicationSettings.EmailSender))
                {
                    return(HttpStatusCode.NotFound);
                }

                string username = Request.Form.username;

                if (String.IsNullOrEmpty(username))
                {
                    this.AddValidationError("username", LanguageResources.Authentication_NameRequired);
                }

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        ChatUser user = repository.GetUserByName(username);

                        if (user == null)
                        {
                            this.AddValidationError("username", String.Format(LanguageResources.Account_NoMatchingUser, username));
                        }
                        else if (String.IsNullOrWhiteSpace(user.Email))
                        {
                            this.AddValidationError("username", String.Format(LanguageResources.Account_NoEmailForUser, username));
                        }
                        else
                        {
                            membershipService.RequestResetPassword(user, applicationSettings.RequestResetPasswordValidThroughInHours);
                            repository.CommitChanges();

                            emailService.SendRequestResetPassword(user, this.Request.Url.SiteBase + "/account/resetpassword/");

                            return(View["requestresetpasswordsuccess", username]);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                return(View["requestresetpassword"]);
            };

            Get["/resetpassword/{id}"] = parameters =>
            {
                if (!applicationSettings.AllowUserResetPassword ||
                    string.IsNullOrWhiteSpace(applicationSettings.EmailSender))
                {
                    return(HttpStatusCode.NotFound);
                }

                string resetPasswordToken = parameters.id;
                string userName           = membershipService.GetUserNameFromToken(resetPasswordToken);

                // Is the token not valid, maybe some character change?
                if (userName == null)
                {
                    return(View["resetpassworderror", LanguageResources.Account_ResetInvalidToken]);
                }
                else
                {
                    ChatUser user = repository.GetUserByRequestResetPasswordId(userName, resetPasswordToken);

                    // Is the token expired?
                    if (user == null)
                    {
                        return(View["resetpassworderror", LanguageResources.Account_ResetExpiredToken]);
                    }
                    else
                    {
                        return(View["resetpassword", user.RequestPasswordResetId]);
                    }
                }
            };

            Post["/resetpassword/{id}"] = parameters =>
            {
                if (!applicationSettings.AllowUserResetPassword ||
                    string.IsNullOrWhiteSpace(applicationSettings.EmailSender))
                {
                    return(HttpStatusCode.NotFound);
                }

                string resetPasswordToken = parameters.id;
                string newPassword        = Request.Form.password;
                string confirmNewPassword = Request.Form.confirmPassword;

                ValidatePassword(newPassword, confirmNewPassword);

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        string   userName = membershipService.GetUserNameFromToken(resetPasswordToken);
                        ChatUser user     = repository.GetUserByRequestResetPasswordId(userName, resetPasswordToken);

                        // Is the token expired?
                        if (user == null)
                        {
                            return(View["resetpassworderror", LanguageResources.Account_ResetExpiredToken]);
                        }
                        else
                        {
                            membershipService.ResetUserPassword(user, newPassword);
                            repository.CommitChanges();

                            return(View["resetpasswordsuccess"]);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                return(View["resetpassword", resetPasswordToken]);
            };
        }
Example #30
0
        public AccountModule(ApplicationSettings applicationSettings,
                             IMembershipService membershipService,
                             IJabbrRepository repository,
                             IAuthenticationService authService,
                             IChatNotificationService notificationService,
                             IUserAuthenticator authenticator,
                             IEmailService emailService)
            : base("/account")
        {
            Get["/"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                return GetProfileView(authService, user);
            };

            Get["/login"] = _ =>
            {
                if (IsAuthenticated)
                {
                    return this.AsRedirectQueryStringOrDefault("~/");
                }

                return View["login", GetLoginViewModel(applicationSettings, repository, authService)];
            };

            Post["/login"] = param =>
            {
                if (!HasValidCsrfTokenOrSecHeader)
                {
                    return HttpStatusCode.Forbidden;
                }

                if (IsAuthenticated)
                {
                    return this.AsRedirectQueryStringOrDefault("~/");
                }

                string username = Request.Form.username;
                string password = Request.Form.password;

                if (String.IsNullOrEmpty(username))
                {
                    this.AddValidationError("username", LanguageResources.Authentication_NameRequired);
                }

                if (String.IsNullOrEmpty(password))
                {
                    this.AddValidationError("password", LanguageResources.Authentication_PassRequired);
                }

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        IList<Claim> claims;
                        if (authenticator.TryAuthenticateUser(username, password, out claims))
                        {
                            return this.SignIn(claims);
                        }
                    }
                }
                catch
                {
                    // Swallow the exception
                }

                this.AddValidationError("_FORM", LanguageResources.Authentication_GenericFailure);

                return View["login", GetLoginViewModel(applicationSettings, repository, authService)];
            };

            Post["/logout"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                var response = Response.AsJson(new { success = true });

                this.SignOut();

                return response;
            };

            Get["/register"] = _ =>
            {
                if (IsAuthenticated)
                {
                    return this.AsRedirectQueryStringOrDefault("~/");
                }

                bool requirePassword = !Principal.Identity.IsAuthenticated;

                if (requirePassword &&
                    !applicationSettings.AllowUserRegistration)
                {
                    return HttpStatusCode.NotFound;
                }

                ViewBag.requirePassword = requirePassword;

                return View["register"];
            };

            Post["/create"] = _ =>
            {
                if (!HasValidCsrfTokenOrSecHeader)
                {
                    return HttpStatusCode.Forbidden;
                }

                bool requirePassword = !Principal.Identity.IsAuthenticated;

                if (requirePassword &&
                    !applicationSettings.AllowUserRegistration)
                {
                    return HttpStatusCode.NotFound;
                }

                if (IsAuthenticated)
                {
                    return this.AsRedirectQueryStringOrDefault("~/");
                }

                ViewBag.requirePassword = requirePassword;

                string username = Request.Form.username;
                string email = Request.Form.email;
                string password = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                if (String.IsNullOrEmpty(username))
                {
                    this.AddValidationError("username", LanguageResources.Authentication_NameRequired);
                }

                if (String.IsNullOrEmpty(email))
                {
                    this.AddValidationError("email", LanguageResources.Authentication_EmailRequired);
                }

                try
                {
                    if (requirePassword)
                    {
                        ValidatePassword(password, confirmPassword);
                    }

                    if (ModelValidationResult.IsValid)
                    {
                        if (requirePassword)
                        {
                            ChatUser user = membershipService.AddUser(username, email, password);

                            return this.SignIn(user);
                        }
                        else
                        {
                            // Add the required claims to this identity
                            var identity = Principal.Identity as ClaimsIdentity;

                            if (!Principal.HasClaim(ClaimTypes.Name))
                            {
                                identity.AddClaim(new Claim(ClaimTypes.Name, username));
                            }

                            if (!Principal.HasClaim(ClaimTypes.Email))
                            {
                                identity.AddClaim(new Claim(ClaimTypes.Email, email));
                            }

                            return this.SignIn(Principal.Claims);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                return View["register"];
            };

            Post["/unlink"] = param =>
            {
                if (!HasValidCsrfTokenOrSecHeader)
                {
                    return HttpStatusCode.Forbidden;
                }

                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                string provider = Request.Form.provider;
                ChatUser user = repository.GetUserById(Principal.GetUserId());

                if (user.Identities.Count == 1 && !user.HasUserNameAndPasswordCredentials())
                {
                    Request.AddAlertMessage("error", LanguageResources.Account_UnlinkRequiresMultipleIdentities);
                    return Response.AsRedirect("~/account/#identityProviders");
                }

                var identity = user.Identities.FirstOrDefault(i => i.ProviderName == provider);

                if (identity != null)
                {
                    repository.Remove(identity);

                    Request.AddAlertMessage("success", String.Format(LanguageResources.Account_UnlinkCompleted, provider));
                    return Response.AsRedirect("~/account/#identityProviders");
                }

                return HttpStatusCode.BadRequest;
            };

            Post["/newpassword"] = _ =>
            {
                if (!HasValidCsrfTokenOrSecHeader)
                {
                    return HttpStatusCode.Forbidden;
                }

                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                string password = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                ValidatePassword(password, confirmPassword);

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.SetUserPassword(user, password);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    Request.AddAlertMessage("success", LanguageResources.Authentication_PassAddSuccess);
                    return Response.AsRedirect("~/account/#changePassword");
                }

                return GetProfileView(authService, user);
            };

            Post["/changepassword"] = _ =>
            {
                if (!HasValidCsrfTokenOrSecHeader)
                {
                    return HttpStatusCode.Forbidden;
                }

                if (!applicationSettings.AllowUserRegistration)
                {
                    return HttpStatusCode.NotFound;
                }

                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                string oldPassword = Request.Form.oldPassword;
                string password = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                if (String.IsNullOrEmpty(oldPassword))
                {
                    this.AddValidationError("oldPassword", LanguageResources.Authentication_OldPasswordRequired);
                }

                ValidatePassword(password, confirmPassword);

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.ChangeUserPassword(user, oldPassword, password);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    Request.AddAlertMessage("success", LanguageResources.Authentication_PassChangeSuccess);
                    return Response.AsRedirect("~/account/#changePassword");
                }

                return GetProfileView(authService, user);
            };

            Post["/changeusername"] = _ =>
            {
                if (!HasValidCsrfTokenOrSecHeader)
                {
                    return HttpStatusCode.Forbidden;
                }

                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                string username = Request.Form.username;
                string confirmUsername = Request.Form.confirmUsername;

                ValidateUsername(username, confirmUsername);

                ChatUser user = repository.GetUserById(Principal.GetUserId());
                string oldUsername = user.Name;

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.ChangeUserName(user, username);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    notificationService.OnUserNameChanged(user, oldUsername, username);

                    Request.AddAlertMessage("success", LanguageResources.Authentication_NameChangeCompleted);
                    return Response.AsRedirect("~/account/#changeUsername");
                }

                return GetProfileView(authService, user);
            };

            Get["/requestresetpassword"] = _ =>
            {
                if (IsAuthenticated)
                {
                    return Response.AsRedirect("~/account/#changePassword");
                }

                if (!Principal.Identity.IsAuthenticated &&
                    !applicationSettings.AllowUserResetPassword ||
                    string.IsNullOrWhiteSpace(applicationSettings.EmailSender))
                {
                    return HttpStatusCode.NotFound;
                }

                return View["requestresetpassword"];
            };

            Post["/requestresetpassword"] = _ =>
            {
                if (!HasValidCsrfTokenOrSecHeader)
                {
                    return HttpStatusCode.Forbidden;
                }

                if (IsAuthenticated)
                {
                    return Response.AsRedirect("~/account/#changePassword");
                }

                if (!Principal.Identity.IsAuthenticated &&
                    !applicationSettings.AllowUserResetPassword ||
                    string.IsNullOrWhiteSpace(applicationSettings.EmailSender))
                {
                    return HttpStatusCode.NotFound;
                }

                string username = Request.Form.username;

                if (String.IsNullOrEmpty(username))
                {
                    this.AddValidationError("username", LanguageResources.Authentication_NameRequired);
                }

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        ChatUser user = repository.GetUserByName(username);

                        if (user == null)
                        {
                            this.AddValidationError("username", String.Format(LanguageResources.Account_NoMatchingUser, username));
                        }
                        else if (String.IsNullOrWhiteSpace(user.Email))
                        {
                            this.AddValidationError("username", String.Format(LanguageResources.Account_NoEmailForUser, username));
                        }
                        else
                        {
                            membershipService.RequestResetPassword(user, applicationSettings.RequestResetPasswordValidThroughInHours);
                            repository.CommitChanges();

                            emailService.SendRequestResetPassword(user, this.Request.Url.SiteBase + "/account/resetpassword/");

                            return View["requestresetpasswordsuccess", username];
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                return View["requestresetpassword"];
            };

            Get["/resetpassword/{id}"] = parameters =>
            {
                if (!applicationSettings.AllowUserResetPassword ||
                    string.IsNullOrWhiteSpace(applicationSettings.EmailSender))
                {
                    return HttpStatusCode.NotFound;
                }

                string resetPasswordToken = parameters.id;
                string userName = membershipService.GetUserNameFromToken(resetPasswordToken);

                // Is the token not valid, maybe some character change?
                if (userName == null)
                {
                    return View["resetpassworderror", LanguageResources.Account_ResetInvalidToken];
                }
                else
                {
                    ChatUser user = repository.GetUserByRequestResetPasswordId(userName, resetPasswordToken);

                    // Is the token expired?
                    if (user == null)
                    {
                        return View["resetpassworderror", LanguageResources.Account_ResetExpiredToken];
                    }
                    else
                    {
                        return View["resetpassword", user.RequestPasswordResetId];
                    }
                }
            };

            Post["/resetpassword/{id}"] = parameters =>
            {
                if (!HasValidCsrfTokenOrSecHeader)
                {
                    return HttpStatusCode.Forbidden;
                }

                if (!applicationSettings.AllowUserResetPassword ||
                    string.IsNullOrWhiteSpace(applicationSettings.EmailSender))
                {
                    return HttpStatusCode.NotFound;
                }

                string resetPasswordToken = parameters.id;
                string newPassword = Request.Form.password;
                string confirmNewPassword = Request.Form.confirmPassword;

                ValidatePassword(newPassword, confirmNewPassword);

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        string userName = membershipService.GetUserNameFromToken(resetPasswordToken);
                        ChatUser user = repository.GetUserByRequestResetPasswordId(userName, resetPasswordToken);

                        // Is the token expired?
                        if (user == null)
                        {
                            return View["resetpassworderror", LanguageResources.Account_ResetExpiredToken];
                        }
                        else
                        {
                            membershipService.ResetUserPassword(user, newPassword);
                            repository.CommitChanges();

                            return View["resetpasswordsuccess"];
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                return View["resetpassword", resetPasswordToken];
            };
        }
Example #31
0
 public UserController(IUserAuthenticator UserAuthenticator, IUserDataAccess UserDataAccess)
 {
     userAuthenticator = UserAuthenticator;
     userDataAccess    = UserDataAccess;
 }
Example #32
0
        public AccountModule(ApplicationSettings applicationSettings,
                             IMembershipService membershipService,
                             IJabbrRepository repository,
                             IAuthenticationService authService,
                             IChatNotificationService notificationService,
                             IUserAuthenticator authenticator)
            : base("/account")
        {
            Get["/"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                return GetProfileView(authService, user);
            };

            Get["/login"] = _ =>
            {
                if (IsAuthenticated)
                {
                    return Response.AsRedirect("~/");
                }

                return View["login", GetLoginViewModel(applicationSettings, repository, authService)];
            };

            Post["/login"] = param =>
            {
                if (IsAuthenticated)
                {
                    return Response.AsRedirect("~/");
                }

                string username = Request.Form.username;
                string password = Request.Form.password;

                if (String.IsNullOrEmpty(username))
                {
                    this.AddValidationError("username", "Name is required");
                }

                if (String.IsNullOrEmpty(password))
                {
                    this.AddValidationError("password", "Password is required");
                }

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        IList<Claim> claims;
                        if (authenticator.TryAuthenticateUser(username, password, out claims))
                        {
                            return this.SignIn(claims);
                        }
                    }
                }
                catch
                {
                    // Swallow the exception
                }

                this.AddValidationError("_FORM", "Login failed. Check your username/password.");

                return View["login", GetLoginViewModel(applicationSettings, repository, authService)];
            };

            Post["/logout"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                var response = Response.AsJson(new { success = true });

                this.SignOut();

                return response;
            };

            Get["/register"] = _ =>
            {
                if (IsAuthenticated)
                {
                    return Response.AsRedirect("~/");
                }

                bool requirePassword = !Principal.Identity.IsAuthenticated;

                if (requirePassword &&
                    !applicationSettings.AllowUserRegistration)
                {
                    return HttpStatusCode.NotFound;
                }

                ViewBag.requirePassword = requirePassword;

                return View["register"];
            };

            Post["/create"] = _ =>
            {
                bool requirePassword = !Principal.Identity.IsAuthenticated;

                if (requirePassword &&
                    !applicationSettings.AllowUserRegistration)
                {
                    return HttpStatusCode.NotFound;
                }

                if (IsAuthenticated)
                {
                    return Response.AsRedirect("~/");
                }

                ViewBag.requirePassword = requirePassword;

                string username = Request.Form.username;
                string email = Request.Form.email;
                string password = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                if (String.IsNullOrEmpty(username))
                {
                    this.AddValidationError("username", "Name is required");
                }

                if (String.IsNullOrEmpty(email))
                {
                    this.AddValidationError("email", "Email is required");
                }

                try
                {
                    if (requirePassword)
                    {
                        ValidatePassword(password, confirmPassword);
                    }

                    if (ModelValidationResult.IsValid)
                    {
                        if (requirePassword)
                        {
                            ChatUser user = membershipService.AddUser(username, email, password);

                            return this.SignIn(user);
                        }
                        else
                        {
                            // Add the required claims to this identity
                            var identity = Principal.Identity as ClaimsIdentity;

                            if (!Principal.HasClaim(ClaimTypes.Name))
                            {
                                identity.AddClaim(new Claim(ClaimTypes.Name, username));
                            }

                            if (!Principal.HasClaim(ClaimTypes.Email))
                            {
                                identity.AddClaim(new Claim(ClaimTypes.Email, email));
                            }

                            return this.SignIn(Principal.Claims);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                return View["register"];
            };

            Post["/unlink"] = param =>
            {
                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                string provider = Request.Form.provider;
                ChatUser user = repository.GetUserById(Principal.GetUserId());

                if (user.Identities.Count == 1 && !user.HasUserNameAndPasswordCredentials())
                {
                    Request.AddAlertMessage("error", "You cannot unlink this account because you would lose your ability to login.");
                    return Response.AsRedirect("~/account/#identityProviders");
                }

                var identity = user.Identities.FirstOrDefault(i => i.ProviderName == provider);

                if (identity != null)
                {
                    repository.Remove(identity);

                    Request.AddAlertMessage("success", String.Format("Successfully unlinked {0} account.", provider));
                    return Response.AsRedirect("~/account/#identityProviders");
                }

                return HttpStatusCode.BadRequest;
            };

            Post["/newpassword"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                string password = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                ValidatePassword(password, confirmPassword);

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.SetUserPassword(user, password);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    Request.AddAlertMessage("success", "Successfully added a password.");
                    return Response.AsRedirect("~/account/#changePassword");
                }

                return GetProfileView(authService, user);
            };

            Post["/changepassword"] = _ =>
            {
                if (!applicationSettings.AllowUserRegistration)
                {
                    return HttpStatusCode.NotFound;
                }

                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                string oldPassword = Request.Form.oldPassword;
                string password = Request.Form.password;
                string confirmPassword = Request.Form.confirmPassword;

                if (String.IsNullOrEmpty(oldPassword))
                {
                    this.AddValidationError("oldPassword", "Old password is required");
                }

                ValidatePassword(password, confirmPassword);

                ChatUser user = repository.GetUserById(Principal.GetUserId());

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.ChangeUserPassword(user, oldPassword, password);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    Request.AddAlertMessage("success", "Successfully changed your password.");
                    return Response.AsRedirect("~/account/#changePassword");
                }

                return GetProfileView(authService, user);
            };

            Post["/changeusername"] = _ =>
            {
                if (!IsAuthenticated)
                {
                    return HttpStatusCode.Forbidden;
                }

                string username = Request.Form.username;
                string confirmUsername = Request.Form.confirmUsername;

                ValidateUsername(username, confirmUsername);

                ChatUser user = repository.GetUserById(Principal.GetUserId());
                string oldUsername = user.Name;

                try
                {
                    if (ModelValidationResult.IsValid)
                    {
                        membershipService.ChangeUserName(user, username);
                        repository.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    this.AddValidationError("_FORM", ex.Message);
                }

                if (ModelValidationResult.IsValid)
                {
                    notificationService.OnUserNameChanged(user, oldUsername, username);

                    Request.AddAlertMessage("success", "Successfully changed your username.");
                    return Response.AsRedirect("~/account/#changeUsername");
                }

                return GetProfileView(authService, user);
            };
        }
 public LoginService(IUserAuthenticator userAuthenticator)
 {
     this.userAuthenticator = userAuthenticator;
 }
Example #34
0
 public LoginService(IUserAuthenticator userAuthenticator)
 {
     this.userAuthenticator = userAuthenticator;
 }
 protected virtual void When_Authenticating_A_Client_WebApi_User()
 {
     Authenticator = new UserAuthenticator(MockWebApiAppSettings.Object);
     IsValid       = Authenticator.IsValid(Username, Password, true);
 }
Example #36
0
 public UserController(IUserAuthenticator userManager)
 {
     _userManager = userManager;
 }
Example #37
0
 public UserAuthenticatorTest()
 {
     _authenticator = new UserAuthenticator(GetMockUserManager().Object);
 }
Example #38
0
 public JwtMiddleware(RequestDelegate next, IUserAuthenticator authenticator, IEnumerable <IUserExtractor> userExtractors)
 {
     _next           = next ?? throw new ArgumentNullException(nameof(next));
     _authenticator  = authenticator ?? throw new ArgumentNullException(nameof(authenticator));
     _userExtractors = userExtractors ?? throw new ArgumentNullException(nameof(userExtractors));
 }
 public UserChecker(IUserAuthenticator userAuthenticator, ILogger <UserChecker> logger)
 {
     this.userAuthenticator = userAuthenticator ?? throw new ArgumentNullException(nameof(userAuthenticator));
     this.logger            = logger ?? throw new ArgumentNullException(nameof(logger));
 }
Example #40
0
        /// <summary>
        /// Sets the User Authenticator.
        /// </summary>
        /// <param name="userAuthenticator">The user authenticator.</param>
        /// <returns>A OptionsBuilder to continue building on.</returns>
        public OptionsBuilder UserAuthenticator(IUserAuthenticator userAuthenticator)
        {
            _options.UserAuthenticator = userAuthenticator;

            return(this);
        }
 public AuthenticateUserQueryHandler(IUserAuthenticator userAuthenticator)
 {
     this.userAuthenticator = userAuthenticator;
 }
Example #42
0
 public AccountController(IUserAuthenticator userAuthenticator, IUserService userService)
 {
     _userAuthenticator = userAuthenticator;
     _userService       = userService;
 }
 public ContactAuthenticationService(IFormsAuthenticationService formsAuthentication, ContactAuthenticator agentAuthenticator, IClarifySessionCache sessionCache)
 {
     _formsAuthentication = formsAuthentication;
     _agentAuthenticator = agentAuthenticator;
     _sessionCache = sessionCache;
 }