コード例 #1
0
 public HistoryViewBehaviour(UserDefinition currentUser) : base(currentUser)
 {
 }
コード例 #2
0
 public Task <IActionResult> Post([FromBody] UserDefinition userDefinition) => WithContextAsync <Organization>(async(contextUser, organization) =>
コード例 #3
0
        public void TestParseMany3()
        {
            var d = UserDefinition.ParseMany("  Atko aTko , ATko; atko AtkO", false);

            Assert.AreEqual(5, d.Count());
        }
コード例 #4
0
 public BrowseItem(UsersBrowseModule module, UserDefinition data)
 {
     Module = module;
     ObjectSupport.CopyData(data, this);
 }
コード例 #5
0
 public DefaultFieldBehaviour(UserDefinition currentUser) : base(currentUser)
 {
 }
コード例 #6
0
 public DefaultViewLinkBehaviour(UserDefinition currentUser) : base(currentUser)
 {
 }
コード例 #7
0
 public TableFooterViewBehaviour(UserDefinition currentUser) : base(currentUser)
 {
 }
コード例 #8
0
 public LabelControlBehaviour(UserDefinition currentUser) : base(currentUser)
 {
 }
コード例 #9
0
 public DownloadFileActionBehaviour(UserDefinition currentUser) : base(currentUser)
 {
 }
コード例 #10
0
 public SearchTicketsWithAutoCompleteBehaviour(UserDefinition currentUser) : base(currentUser)
 {
 }
コード例 #11
0
 public DefaultSectionBehaviour(UserDefinition currentUser) : base(currentUser)
 {
 }
コード例 #12
0
ファイル: UsersEdit.cs プロジェクト: moayyaed/YetaWF-Modules
        public async Task <ActionResult> UsersEdit_Partial(EditModel model)
        {
            using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
                string         originalUserName = model.OriginalUserName;
                UserDefinition user             = await dataProvider.GetItemAsync(originalUserName);

                if (user == null)
                {
                    throw new Error(this.__ResStr("alreadyDeleted", "The user named \"{0}\" has been removed and can no longer be updated.", originalUserName));
                }
                if (!ModelState.IsValid)
                {
                    return(PartialView(model));
                }

                LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

                switch (config.RegistrationType)
                {
                case RegistrationTypeEnum.NameAndEmail: {
                    List <DataProviderFilterInfo> filters = DataProviderFilterInfo.Join(null, new DataProviderFilterInfo {
                            Field = nameof(UserDefinition.Email), Operator = "==", Value = model.Email,
                        });
                    UserDefinition userExists = await dataProvider.GetItemAsync(filters);

                    if (userExists != null && user.UserName != userExists.UserName)
                    {
                        ModelState.AddModelError(nameof(model.Email), this.__ResStr("emailUsed", "An account using email address {0} already exists.", model.Email));
                        return(PartialView(model));
                    }
                    break;
                }

                case RegistrationTypeEnum.EmailOnly:
                    model.UserName = model.Email;
                    break;

                case RegistrationTypeEnum.NameOnly:
                    model.Email = model.UserName;
                    break;
                }

                user = model.GetData(user); // merge new data into original
                model.SetData(user);        // and all the data back into model for final display

                switch (await dataProvider.UpdateItemAsync(originalUserName, user))
                {
                default:
                case UpdateStatusEnum.RecordDeleted:
                    throw new Error(this.__ResStr("alreadyDeleted", "The user named \"{0}\" has been removed and can no longer be updated.", originalUserName));

                case UpdateStatusEnum.NewKeyExists:
                    ModelState.AddModelError(nameof(model.UserName), this.__ResStr("alreadyExists", "A user named \"{0}\" already exists.", model.UserName));
                    return(PartialView(model));

                case UpdateStatusEnum.OK:
                    break;
                }
                return(FormProcessed(model, this.__ResStr("okSaved", "User updated"), OnPopupClose: OnPopupCloseEnum.ReloadModule));
            }
        }
コード例 #13
0
ファイル: UsersEdit.cs プロジェクト: moayyaed/YetaWF-Modules
 public void SetData(UserDefinition user)
 {
     ObjectSupport.CopyData(user, this);
     OriginalUserName = user.UserName;
 }
コード例 #14
0
ファイル: UsersEdit.cs プロジェクト: moayyaed/YetaWF-Modules
 public UserDefinition GetData(UserDefinition user)
 {
     ObjectSupport.CopyData(this, user);
     return(user);
 }
コード例 #15
0
        protected void Application_Start()
        {
            var formatters = GlobalConfiguration.Configuration.Formatters;

            formatters.Remove(formatters.XmlFormatter);

            LiveConfigurationManager.Reload(ConfigurationManager.AppSettings);
            LiveConfigurationManager.Start();

            //forces Rules Engine to load
            var x = VoatRulesEngine.Instance;
            //forces thumbgenerator to initialize
            var p = ThumbGenerator.DestinationPathThumbs;

            if (!Settings.SignalRDisabled)
            {
                Microsoft.AspNet.SignalR.GlobalHost.DependencyResolver.Register(typeof(Microsoft.AspNet.SignalR.Hubs.IJavaScriptMinifier), () => new HubMinifier());
            }
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //register global error handler
            GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new VoatExceptionLogger());

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());

            ModelMetadataProviders.Current = new CachedDataAnnotationsModelMetadataProvider();

            JsonConvert.DefaultSettings = () => { return(JsonSettings.GetSerializationSettings()); };

            #region Hook Events

            EventHandler <MessageReceivedEventArgs> updateNotificationCount = delegate(object s, MessageReceivedEventArgs e)
            {
                if (!Settings.SignalRDisabled)
                {
                    var userDef = UserDefinition.Parse(e.TargetUserName);
                    if (userDef.Type == IdentityType.User)
                    {
                        //get count of unread notifications
                        var q = new QueryMessageCounts(userDef.Name, userDef.Type, MessageTypeFlag.All, MessageState.Unread);
                        var unreadNotifications = q.Execute().Total;
                        // send SignalR realtime notification to recipient
                        var hubContext = GlobalHost.ConnectionManager.GetHubContext <MessagingHub>();
                        hubContext.Clients.User(e.TargetUserName).setNotificationsPending(unreadNotifications);
                    }
                }
            };
            EventNotification.Instance.OnMessageReceived      += updateNotificationCount;
            EventNotification.Instance.OnMentionReceived      += updateNotificationCount;
            EventNotification.Instance.OnCommentReplyReceived += updateNotificationCount;

            EventNotification.Instance.OnVoteReceived += (s, e) =>
            {
                if (!Settings.SignalRDisabled)
                {
                    var hubContext = GlobalHost.ConnectionManager.GetHubContext <MessagingHub>();
                    switch (e.ReferenceType)
                    {
                    case Domain.Models.ContentType.Submission:
                        hubContext.Clients.User(e.TargetUserName).voteChange(1, e.ChangeValue);
                        break;

                    case Domain.Models.ContentType.Comment:
                        hubContext.Clients.User(e.TargetUserName).voteChange(2, e.ChangeValue);
                        break;
                    }
                }
            };

            //TODO: Fuzzy can't wait for this feature!
            EventNotification.Instance.OnHeadButtReceived    += (s, e) => { };
            EventNotification.Instance.OnChatMessageReceived += (s, e) => { };

            #endregion


            //BLOCK: Temp Log ThreadPool Stats
            timer = new Timer(new TimerCallback(o => {
                int workerThreads;
                int completionPortThreads;
                int maxWorkerThreads;
                int maxCompletionPortThreads;

                ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
                ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxCompletionPortThreads);

                var data = new
                {
                    InUse   = maxWorkerThreads - workerThreads,
                    InUseIO = maxCompletionPortThreads - completionPortThreads,
                    AvailableWorkerThreads = workerThreads,
                    AvailableIOThreads     = completionPortThreads,
                    MaxWorkerThreads       = maxWorkerThreads,
                    MaxIOThreads           = maxCompletionPortThreads
                };


                var logEntry = new LogInformation
                {
                    Origin   = Settings.Origin.ToString(),
                    Type     = LogType.Debug,
                    UserName = null,
                    Message  = "ThreadPool Stats",
                    Category = "Monitor",
                    Data     = data
                };

                EventLogger.Instance.Log(logEntry);
            }), null, TimeSpan.Zero, TimeSpan.FromSeconds(15));


            // USE ONLY FOR DEBUG: clear all sessions used for online users count
            // SessionTracker.RemoveAllSessions();
        }
コード例 #16
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                throw new Error(this.__ResStr("extErr", "The external login provider reported this error: {0}", remoteError));
            }

            SignInManager <UserDefinition> _signinManager = (SignInManager <UserDefinition>)YetaWFManager.ServiceProvider.GetService(typeof(SignInManager <UserDefinition>));
            ExternalLoginInfo loginInfo = await _signinManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                Logging.AddErrorLog("AuthenticationManager.GetExternalLoginInfoAsync() returned null");
                return(Redirect(Helper.GetSafeReturnUrl(Manager.CurrentSite.LoginUrl)));
            }
            using (LoginConfigDataProvider logConfigDP = new LoginConfigDataProvider()) {
                List <LoginConfigDataProvider.LoginProviderDescription> loginProviders = await logConfigDP.GetActiveExternalLoginProvidersAsync();

                if ((from l in loginProviders where l.InternalName == loginInfo.LoginProvider select l).FirstOrDefault() == null)
                {
                    Logging.AddErrorLog("Callback from external login provider {0} which is not active", loginInfo.LoginProvider);
                    return(Redirect(Helper.GetSafeReturnUrl(Manager.CurrentSite.LoginUrl)));
                }
            }

            // get our registration defaults
            LoginConfigData config = await LoginConfigDataProvider.GetConfigAsync();

            // Sign in the user with this external login provider if the user already has a login
            UserDefinition user = await Managers.GetUserManager().FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey);

            if (user == null)
            {
                // If the user does not have an account, then prompt the user to create an account
                // we will go to a page where the user can set up a local account
                Manager.OriginList = new List <Origin>();
                if (!string.IsNullOrWhiteSpace(returnUrl))
                {
                    Manager.OriginList.Add(new Origin()
                    {
                        Url = returnUrl
                    });                                                      // where to go after setup
                }
                Manager.OriginList.Add(new Origin()
                {
                    Url = Helper.GetSafeReturnUrl(Manager.CurrentSite.ExternalAccountSetupUrl)
                });                                                                                                                  // setup
                return(Redirect(Manager.ReturnToUrl));
            }

            if (string.IsNullOrWhiteSpace(returnUrl) && Manager.HaveReturnToUrl)
            {
                returnUrl = Manager.ReturnToUrl;
            }
            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                returnUrl = await Resource.ResourceAccess.GetUserPostLoginUrlAsync((from u in user.RolesList select u.RoleId).ToList());
            }
            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                returnUrl = Manager.CurrentSite.PostLoginUrl;
            }
            returnUrl = Helper.GetSafeReturnUrl(returnUrl);

            // determine what to do based on account status
            if (user.UserStatus == UserStatusEnum.Approved)
            {
                await LoginModuleController.UserLoginAsync(user);

                Logging.AddLog("User {0} - logged on", user.UserName);
                returnUrl = QueryHelper.AddRando(returnUrl); // to defeat client-side caching
                return(Redirect(returnUrl));
            }
            else if (user.UserStatus == UserStatusEnum.Rejected)
            {
                await LoginModuleController.UserLogoffAsync();

                Logging.AddErrorLog("User {0} - rejected user", user.UserName);
                if (string.IsNullOrWhiteSpace(config.RejectedUrl))
                {
                    return(Redirect(MessageUrl("Your account has been rejected by the site administrator.")));
                }
                return(Redirect(Helper.GetSafeReturnUrl(config.RejectedUrl)));
            }
            else if (user.UserStatus == UserStatusEnum.Suspended)
            {
                await LoginModuleController.UserLogoffAsync();

                Logging.AddErrorLog("User {0} - suspended user", user.UserName);
                if (string.IsNullOrWhiteSpace(config.SuspendedUrl))
                {
                    return(Redirect(MessageUrl("Your account has been suspended by the site administrator.")));
                }
                return(Redirect(Helper.GetSafeReturnUrl(config.SuspendedUrl)));
            }
            else if (user.UserStatus == UserStatusEnum.NeedValidation)
            {
                await LoginModuleController.UserLogoffAsync();

                Logging.AddErrorLog("User {0} - not yet validated", user.UserName);
                if (string.IsNullOrWhiteSpace(config.VerificationPendingUrl))
                {
                    return(Redirect(MessageUrl(this.__ResStr("notValidated", "Your account has not yet been verified. You will receive an email with verification information. Once received, please use the information in the email to complete the registration."))));
                }
                return(Redirect(Helper.GetSafeReturnUrl(config.VerificationPendingUrl)));
            }
            else if (user.UserStatus == UserStatusEnum.NeedApproval)
            {
                await LoginModuleController.UserLogoffAsync();

                Logging.AddErrorLog("User {0} - not yet approved", user.UserName);
                if (string.IsNullOrWhiteSpace(config.ApprovalPendingUrl))
                {
                    return(Redirect(MessageUrl(this.__ResStr("notApproved", "Your account has not yet been approved by the site administrator. You will receive an email confirmation as soon as your account is active."))));
                }
                return(Redirect(Helper.GetSafeReturnUrl(config.ApprovalPendingUrl)));
            }
            else
            {
                await LoginModuleController.UserLogoffAsync();

                throw new InternalError("badUserStatus", "Unexpected account status {0}", user.UserStatus);
            }
        }
コード例 #17
0
        public async Task <DataProviderGetRecords <UserDefinition> > GetItemsAsync(int skip, int take, List <DataProviderSortInfo> sort, List <DataProviderFilterInfo> filters, bool IncludeSuperuser = true)
        {
            if (IncludeSuperuser && SuperuserDefinitionDataProvider.SuperuserAvailable)
            {
                UserDefinition superuser = null;
                int            origSkip = skip, origTake = take;

                using (SuperuserDefinitionDataProvider superDP = new SuperuserDefinitionDataProvider()) {
                    superuser = await superDP.GetItemAsync(filters);
                }

                DataProviderGetRecords <UserDefinition> recs = new DataProviderGetRecords <UserDefinition>();

                recs.Total = 0;
                if (superuser != null)
                {
                    recs.Total = 1;
                    if (skip > 0)
                    {
                        superuser = null;
                        --skip;
                    }
                    else
                    {
                        if (take > 0)
                        {
                            take--;
                        }
                    }
                }

                int userTotal = 0;
                if (take == 0 && origTake > 0)
                {
                    // we just need the total
                    List <DataProviderFilterInfo> newfilters = null;
                    newfilters = DataProviderFilterInfo.Join(newfilters, new DataProviderFilterInfo {
                        Field = nameof(UserDefinition.UserName), Operator = "==", Value = null
                    });
                    DataProviderGetRecords <UserDefinition> trecs = await DataProvider.GetRecordsAsync(0, 1, sort, newfilters);

                    userTotal = trecs.Total;
                    recs.Data = new List <UserDefinition>();
                }
                else
                {
                    DataProviderGetRecords <UserDefinition> trecs = await DataProvider.GetRecordsAsync(skip, take, sort, filters);

                    userTotal = trecs.Total;
                    recs.Data = trecs.Data;
                }
                if (superuser != null)
                {
                    recs.Data.Insert(0, superuser);
                }
                recs.Total += userTotal;
                return(recs);
            }
            else
            {
                return(await DataProvider.GetRecordsAsync(skip, take, sort, filters));
            }
        }
コード例 #18
0
 public GotoActionBehaviour(UserDefinition currentUser) : base(currentUser)
 {
 }
コード例 #19
0
        public async Task <IActionResult> Post([FromBody] UserDefinition userDefinition)
        {
            if (userDefinition is null)
            {
                throw new ArgumentNullException(nameof(userDefinition));
            }

            if (!ProjectId.HasValue)
            {
                return(ErrorResult
                       .BadRequest($"Project Id provided in the url path is invalid.  Must be a valid GUID.", ResultErrorCode.ValidationError)
                       .ActionResult());
            }

            var validation = new UserDefinitionValidator().Validate(userDefinition);

            if (!validation.IsValid)
            {
                return(ErrorResult
                       .BadRequest(validation)
                       .ActionResult());
            }

            var project = await projectsRepository
                          .GetAsync(ProjectId.Value)
                          .ConfigureAwait(false);

            if (project is null)
            {
                return(ErrorResult
                       .NotFound($"A Project with the ID '{ProjectId.Value}' could not be found in this TeamCloud Instance.")
                       .ActionResult());
            }

            var newUser = await userService
                          .GetUserAsync(userDefinition)
                          .ConfigureAwait(false);

            if (newUser is null)
            {
                return(ErrorResult
                       .NotFound($"A User with the Email '{userDefinition.Email}' could not be found.")
                       .ActionResult());
            }

            if (project.Users.Contains(newUser))
            {
                return(ErrorResult
                       .Conflict($"A User with the Email '{userDefinition.Email}' already exists on this Project. Please try your request again with a unique email or call PUT to update the existing User.")
                       .ActionResult());
            }

            var command = new OrchestratorProjectUserCreateCommand(CurrentUser, newUser, ProjectId.Value);

            var commandResult = await orchestrator
                                .InvokeAsync(command)
                                .ConfigureAwait(false);

            if (commandResult.Links.TryGetValue("status", out var statusUrl))
            {
                return(StatusResult
                       .Accepted(commandResult.CommandId.ToString(), statusUrl, commandResult.RuntimeStatus.ToString(), commandResult.CustomStatus)
                       .ActionResult());
            }

            throw new Exception("This shoudn't happen, but we need to decide to do when it does.");
        }
コード例 #20
0
 public DefaultControlBehaviour(UserDefinition currentUser) : base(currentUser)
 {
 }
コード例 #21
0
        private async Task <ActionResult> CompleteLoginAsync(LoginModel model, LoginConfigData config, bool useTwoStep)
        {
            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_USERID);
            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_NEXTURL);
            Manager.SessionSettings.SiteSettings.ClearValue(LoginTwoStepController.IDENTITY_TWOSTEP_CLOSEONLOGIN);
            Manager.SessionSettings.SiteSettings.Save();
            model.Success = false;

            // make sure it's a valid user
            UserDefinition user = await Managers.GetUserManager().FindByNameAsync(model.UserName);

            if (user == null)
            {
                Logging.AddErrorLog("User login failed: {0} - no such user", model.UserName);
                ModelState.AddModelError(nameof(LoginModel.Email), this.__ResStr("invLogin", "Invalid user name or password"));
                ModelState.AddModelError(nameof(LoginModel.UserName), this.__ResStr("invLogin", "Invalid user name or password"));
                ModelState.AddModelError(nameof(LoginModel.Password), this.__ResStr("invLogin", "Invalid user name or password"));
                return(PartialView(model));
            }
            using (UserLoginInfoDataProvider logInfoDP = new UserLoginInfoDataProvider()) {
                if (await logInfoDP.IsExternalUserAsync(user.UserId))
                {
                    throw new Error(this.__ResStr("extUser", "This account can only be accessed using an external login provider"));
                }
            }

            TwoStepAuth twoStep = new TwoStepAuth();// clear any two-step info we may have
            await twoStep.ClearTwoStepAutheticationAsync(user.UserId);

            if (config.MaxLoginFailures != 0 && user.LoginFailures >= config.MaxLoginFailures)
            {
                ModelState.AddModelError(nameof(LoginModel.Email), this.__ResStr("maxAttemps", "The maximum number of login attempts has been exceeded - Your account has been suspended"));
                ModelState.AddModelError(nameof(LoginModel.UserName), this.__ResStr("maxAttemps", "The maximum number of login attempts has been exceeded - Your account has been suspended"));
                if (user.UserStatus != UserStatusEnum.Suspended)
                {
                    user.UserStatus = UserStatusEnum.Suspended;
                    await Managers.GetUserManager().UpdateAsync(user);
                }
                return(PartialView(model));
            }

            UserDefinition foundUser = user;

            user = null;

            // Handle random super user password (only supported on Core)
            if (foundUser.UserId == SuperuserDefinitionDataProvider.SuperUserId && SuperuserDefinitionDataProvider.SuperuserAvailable && SuperuserDefinitionDataProvider.SuperUserPasswordRandom &&
                model.UserName == SuperuserDefinitionDataProvider.SuperUserName && model.Password == SuperuserDefinitionDataProvider.SuperUserPassword)
            {
                user = foundUser;
            }

            if (user == null)
            {
                user = await Managers.GetUserManager().FindByNameAsync(model.UserName);

                if (string.IsNullOrWhiteSpace(model.Password) || !await Managers.GetUserManager().CheckPasswordAsync(user, model.Password))
                {
                    user = null;
                }
            }
            if (user == null)
            {
                foundUser.LoginFailures = foundUser.LoginFailures + 1;
                await Managers.GetUserManager().UpdateAsync(foundUser);

                Logging.AddErrorLog("User login failed: {0}, {1}, {2}", model.UserName, model.Password, model.VerificationCode);
                ModelState.AddModelError(nameof(LoginModel.Email), this.__ResStr("invLogin", "Invalid user name or password"));
                ModelState.AddModelError(nameof(LoginModel.UserName), this.__ResStr("invLogin", "Invalid user name or password"));
                ModelState.AddModelError(nameof(LoginModel.Password), this.__ResStr("invLogin", "Invalid user name or password"));
                return(PartialView(model));
            }

            // if verification code valid, advance user to approved or needs approval
            if (user.UserStatus == UserStatusEnum.NeedValidation && model.VerificationCode == user.VerificationCode)
            {
                Logging.AddLog("User {0} validated ({1})", model.UserName, model.VerificationCode);

                if (config.ApproveNewUsers)
                {
                    user.UserStatus       = UserStatusEnum.NeedApproval;
                    user.LastActivityDate = DateTime.UtcNow;
                    user.LastActivityIP   = Manager.UserHostAddress;
                    await Managers.GetUserManager().UpdateAsync(user);

                    Emails emails = new Emails();
                    await emails.SendApprovalNeededAsync(user);

                    string nextPage = string.IsNullOrWhiteSpace(config.ApprovalPendingUrl) ? Manager.CurrentSite.HomePageUrl : config.ApprovalPendingUrl;
                    return(FormProcessed(model,
                                         this.__ResStr("notApproved", "You just verified your account. Now your account has to be approved by the site administrator. You will receive an email confirmation as soon as your account is active."),
                                         NextPage: nextPage));
                }
                user.UserStatus = UserStatusEnum.Approved;
                // this is saved below, before we're logged in
            }

            // check what to do based on account status
            if (user.UserStatus == UserStatusEnum.NeedValidation)
            {
                if (model.ShowVerification)
                {
                    Logging.AddErrorLog("User {0} - invalid verification code({1})", model.UserName, model.VerificationCode);
                    ModelState.AddModelError(nameof(LoginModel.VerificationCode), this.__ResStr("invVerification", "The verification code is invalid. Please make sure to copy/paste it from the email to avoid any typos."));
                    user.LoginFailures = user.LoginFailures + 1;
                    await Managers.GetUserManager().UpdateAsync(user);
                }
                else
                {
                    ModelState.AddModelError(nameof(LoginModel.VerificationCode), this.__ResStr("notValidated", "Your account has not yet been verified. You will receive an email with verification information. Please copy and enter the verification code here."));
                }
                model.ShowVerification       = true;
                model.ResendVerificationCode = await Module.GetAction_ResendVerificationEmailAsync(user.UserName);

                model.ShowCaptcha = false;
                return(PartialView(model));
            }
            else if (user.UserStatus == UserStatusEnum.NeedApproval)
            {
                Logging.AddErrorLog("User {0} - not yet approved", model.UserName);
                string nextPage = string.IsNullOrWhiteSpace(config.ApprovalPendingUrl) ? Manager.CurrentSite.HomePageUrl : config.ApprovalPendingUrl;
                return(FormProcessed(model,
                                     this.__ResStr("notApproved2", "Your account has not yet been approved by the site administrator. You will receive an email confirmation as soon as your account is active."),
                                     NextPage: nextPage));
            }
            else if (user.UserStatus == UserStatusEnum.Rejected)
            {
                Logging.AddErrorLog("User {0} - rejected user", model.UserName);
                string nextPage = string.IsNullOrWhiteSpace(config.RejectedUrl) ? Manager.CurrentSite.HomePageUrl : config.RejectedUrl;
                return(FormProcessed(model,
                                     this.__ResStr("accountRejected", "Your account has been rejected by the site administrator."),
                                     NextPage: nextPage));
            }
            else if (user.UserStatus == UserStatusEnum.Suspended)
            {
                Logging.AddErrorLog("User {0} - suspended user", model.UserName);
                string nextPage = string.IsNullOrWhiteSpace(config.SuspendedUrl) ? Manager.CurrentSite.HomePageUrl : config.SuspendedUrl;
                return(FormProcessed(model,
                                     this.__ResStr("accountSuspended", "Your account has been suspended."),
                                     NextPage: nextPage));
            }
            else if (user.UserStatus == UserStatusEnum.Approved)
            {
                string nextUrl = null;
                if (Manager.HaveReturnToUrl)
                {
                    nextUrl = Manager.ReturnToUrl;
                }
                if (string.IsNullOrWhiteSpace(nextUrl))
                {
                    nextUrl = await Resource.ResourceAccess.GetUserPostLoginUrlAsync((from u in user.RolesList select u.RoleId).ToList());
                }
                if (string.IsNullOrWhiteSpace(nextUrl))
                {
                    nextUrl = Manager.CurrentSite.PostLoginUrl;
                }
                if (string.IsNullOrWhiteSpace(nextUrl))
                {
                    nextUrl = YetaWFManager.Manager.CurrentSite.HomePageUrl;
                }

                if (useTwoStep)
                {
                    ActionResult actionResult = await TwoStepAuthetication(user);

                    if (actionResult != null)
                    {
                        Manager.SessionSettings.SiteSettings.SetValue <int>(LoginTwoStepController.IDENTITY_TWOSTEP_USERID, user.UserId);// marker that user has entered correct name/password
                        Manager.SessionSettings.SiteSettings.SetValue <string>(LoginTwoStepController.IDENTITY_TWOSTEP_NEXTURL, nextUrl);
                        Manager.SessionSettings.SiteSettings.SetValue <bool>(LoginTwoStepController.IDENTITY_TWOSTEP_CLOSEONLOGIN, model.CloseOnLogin);
                        Manager.SessionSettings.SiteSettings.Save();
                        return(actionResult);
                    }
                }
                await LoginModuleController.UserLoginAsync(user, model.RememberMe);

                model.Success = true;
                Logging.AddLog("User {0} - logged on", model.UserName);

                return(FormProcessed(model, OnClose: OnCloseEnum.GotoNewPage, OnPopupClose: OnPopupCloseEnum.GotoNewPage, NextPage: nextUrl, ForceRedirect: true));
            }
            else
            {
                throw new InternalError("badUserStatus", "Unexpected account status {0}", user.UserStatus);
            }
        }
コード例 #22
0
        public void TestParseMany2()
        {
            var d = UserDefinition.ParseMany("  Atko aTko , ATko; atko AtkO; atko, atko, atko    atko");

            Assert.AreEqual(1, d.Count());
        }
コード例 #23
0
 public ButtonPageNumberControlBehaviour(UserDefinition currentUser) : base(currentUser)
 {
 }
コード例 #24
0
        public void TestParseMany4()
        {
            var d = UserDefinition.ParseMany(" /u /Atko PuttItOut, Fuzzy.Words, @v/test, @Amalek,   u/Mick; /u/moe", false);

            Assert.AreEqual(6, d.Count());
        }
コード例 #25
0
ファイル: UserService.cs プロジェクト: microsoft/TeamCloud
    public async Task <User> ResolveUserAsync(string organizationId, string organizationName, UserDefinition userDefinition, UserType userType = UserType.User)
    {
        if (userDefinition is null)
        {
            throw new ArgumentNullException(nameof(userDefinition));
        }

        var userId = await GetUserIdAsync(userDefinition.Identifier)
                     .ConfigureAwait(false);

        if (string.IsNullOrEmpty(userId))
        {
            return(null);
        }

        var user = await userRepository
                   .GetAsync(organizationId, userId)
                   .ConfigureAwait(false);

        user ??= new User
        {
            Id               = userId,
            UserType         = userType,
            Organization     = organizationId,
            OrganizationName = organizationName
        };

        return(user);
    }
コード例 #26
0
        private async Task GenerateRecoveryCodeAsync(UserDefinitionDataProvider userDP, UserDefinition user)
        {
            user.RecoveryCode = Guid.NewGuid().ToString().Substring(0, 12);
            UpdateStatusEnum status = await userDP.UpdateItemAsync(user);

            if (status != UpdateStatusEnum.OK)
            {
                throw new Error(this.__ResStr("cantUpdate", "Updating user information failed - {0}", status));
            }
        }
コード例 #27
0
 public CreateDocumentActionBehaviour(UserDefinition currentUser) : base(currentUser)
 {
 }
コード例 #28
0
        private bool ValidateExistingUser(ref string username, string password, UserDefinition user)
        {
            username = user.Username;

            if (user.IsActive != 1)
            {
                if (Log.IsInfoEnabled)
                {
                    Log.Error(String.Format("Inactive user login attempt: {0}", username), this.GetType());
                }

                return(false);
            }

            // prevent more than 50 invalid login attempts in 30 minutes
            var throttler = new Throttler("ValidateUser:"******"site" || user.Source == "sign" || directoryService == null)
            {
                if (validatePassword())
                {
                    throttler.Reset();
                    return(true);
                }

                return(false);
            }

            if (user.Source != "ldap")
            {
                throw new ArgumentOutOfRangeException("userSource");
            }

            if (!string.IsNullOrEmpty(user.PasswordHash) &&
                user.LastDirectoryUpdate != null &&
                user.LastDirectoryUpdate.Value.AddHours(1) >= DateTime.Now)
            {
                if (validatePassword())
                {
                    throttler.Reset();
                    return(true);
                }

                return(false);
            }

            DirectoryEntry entry;

            try
            {
                entry = directoryService.Validate(username, password);
                if (entry == null)
                {
                    return(false);
                }

                throttler.Reset();
            }
            catch (Exception ex)
            {
                Log.Error("Error on directory access", ex, this.GetType());

                // couldn't access directory. allow user to login with cached password
                if (!user.PasswordHash.IsTrimmedEmpty())
                {
                    if (validatePassword())
                    {
                        throttler.Reset();
                        return(true);
                    }

                    return(false);
                }

                throw;
            }

            try
            {
                string salt        = user.PasswordSalt.TrimToNull();
                var    hash        = UserRepository.GenerateHash(password, ref salt);
                var    displayName = entry.FirstName + " " + entry.LastName;
                var    email       = entry.Email.TrimToNull() ?? user.Email ?? (username + "@yourdefaultdomain.com");

                using (var connection = SqlConnections.NewFor <UserRow>())
                    using (var uow = new UnitOfWork(connection))
                    {
                        var fld = UserRow.Fields;
                        new SqlUpdate(fld.TableName)
                        .Set(fld.DisplayName, displayName)
                        .Set(fld.PasswordHash, hash)
                        .Set(fld.PasswordSalt, salt)
                        .Set(fld.Email, email)
                        .Set(fld.LastDirectoryUpdate, DateTime.Now)
                        .WhereEqual(fld.UserId, user.UserId)
                        .Execute(connection, ExpectedRows.One);

                        uow.Commit();

                        UserRetrieveService.RemoveCachedUser(user.UserId, username);
                    }

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error("Error while updating directory user", ex, this.GetType());
                return(true);
            }
        }
コード例 #29
0
 public AllEntry(UserDefinition user)
 {
     ObjectSupport.CopyData(user, this);
 }
コード例 #30
0
        private bool ValidateExistingUser(ref string username, string password, UserDefinition user)
        {
            username = user.Username;

            if (user.IsActive != 1)
            {
                if (Log.IsInfoEnabled)
                    Log.Error(String.Format("Inactive user login attempt: {0}", username), this.GetType());

                return false;
            }

            // prevent more than 50 invalid login attempts in 30 minutes
            var throttler = new Throttler("ValidateUser:"******"site" || user.Source == "sign" || directoryService == null)
            {
                if (validatePassword())
                {
                    throttler.Reset();
                    return true;
                }

                return false;
            }

            if (user.Source != "ldap")
                throw new ArgumentOutOfRangeException("userSource");

            if (!string.IsNullOrEmpty(user.PasswordHash) &&
                user.LastDirectoryUpdate != null &&
                user.LastDirectoryUpdate.Value.AddHours(1) >= DateTime.Now)
            {
                if (validatePassword())
                {
                    throttler.Reset();
                    return true;
                }

                return false;
            }

            DirectoryEntry entry;
            try
            {
                entry = directoryService.Validate(username, password);
                if (entry == null)
                    return false;

                throttler.Reset();
            }
            catch (Exception ex)
            {
                Log.Error("Error on directory access", ex, this.GetType());

                // couldn't access directory. allow user to login with cached password
                if (!user.PasswordHash.IsTrimmedEmpty())
                {
                    if (validatePassword())
                    {
                        throttler.Reset();
                        return true;
                    }

                    return false;
                }

                throw;
            }

            try
            {
                string salt = user.PasswordSalt.TrimToNull();
                var hash = UserRepository.GenerateHash(password, ref salt);
                var displayName = entry.FirstName + " " + entry.LastName;
                var email = entry.Email.TrimToNull() ?? user.Email ?? (username + "@yourdefaultdomain.com");

                using (var connection = SqlConnections.NewFor<UserRow>())
                using (var uow = new UnitOfWork(connection))
                {
                    var fld = UserRow.Fields;
                    new SqlUpdate(fld.TableName)
                        .Set(fld.DisplayName, displayName)
                        .Set(fld.PasswordHash, hash)
                        .Set(fld.PasswordSalt, salt)
                        .Set(fld.Email, email)
                        .Set(fld.LastDirectoryUpdate, DateTime.Now)
                        .WhereEqual(fld.UserId, user.UserId)
                        .Execute(connection, ExpectedRows.One);

                    uow.Commit();

                    UserRetrieveService.RemoveCachedUser(user.UserId, username);
                }

                return true;
            }
            catch (Exception ex)
            {
                Log.Error("Error while updating directory user", ex, this.GetType());
                return true;
            }
        }
コード例 #31
0
 public ButtonSearchControlBehaviour(UserDefinition currentUser) : base(currentUser)
 {
 }