public Identity CreateIdentity(string email, string password, Roles role = Roles.User)
        {
            Identity result = null;

            var identity = new Identity ()
            {
                ExternalIdentifier = Guid.NewGuid().ToString(),
                Email = email,
                Password = this._PasswordUtility.HashPassword(password ?? this._PasswordUtility.Generate ()),
                Role = role
            };

            result = this._IdentityRepository.Add (identity);

            this._Logger.Debug("Identity created : {0}", result != null);

            if (result != null) {
                try
                {
                    var configuration = ConfigurationHelper.Get<ApplicationConfiguration> ();

                    if (configuration != null) {
                        this.SendIdentityEmail (identity, "AccountActivation");
                    }
                }
                catch(Exception exception)
                {
                    this._Logger.ErrorException("Erreur lors de l'envoi du mail d'activation à " + email + " : " + exception.ToString(), exception);
                }
            }

            return result;
        }
Esempio n. 2
0
		/// <summary>
		/// Construct instance from existing data. This is the constructor invoked by 
		/// Gentle when creating new User instances from result sets.
		/// </summary>
		public User( int userId, string firstName, string lastName, Roles primaryRole )
		{
			id = userId;
			this.firstName = firstName;
			this.lastName = lastName;
			this.primaryRole = primaryRole;
		}
Esempio n. 3
0
 public static void BindAdminRegionsDropDown(String empNo, Roles role, ICacheStorage adapter, DropDownList d)
 {
     d.DataSource = BllAdmin.GetRegionsByRights(empNo, role, adapter);
     d.DataTextField = "Value";
     d.DataValueField = "Key";
     d.DataBind();
 }
Esempio n. 4
0
 public User(string username, string password, Roles role)
 {
     this.Username = username;
     this.PasswordHash = password;
     this.Role = role;
     this.Bookings = new List<Booking>();
 }
Esempio n. 5
0
        public Roles getRoles(User secureuser)
        {
            var userRoles = new Roles();
            string strQuery = "SELECT dbo.udf_GetEmployeeType(@cUser_Cd) AS EmployeeType_Txt ";
            var employeeType = (_connection.Query<EmployeeType>(strQuery, new { cUser_Cd = secureuser.Id }).SingleOrDefault());
            if(employeeType == null)
                throw new Exception("Something Bad Happened");
            employeeType.Initialize();

            if (employeeType.IsAdmin)
            {
                userRoles = userRoles | Roles.Admin;
            }
            else if (employeeType.IsManager)
            {
                strQuery = "select Access_Cd from Security..UserSettings where User_Cd = @cUser_Cd";
                var managerType = (_connection.Query<string>(strQuery, new { cUser_Cd = secureuser.Id }).SingleOrDefault());
                if(managerType == null)
                    throw new Exception("Something Bad Happened");
                managerType = managerType.Trim();
                if(managerType.Equals("D"))
                    userRoles = userRoles | Roles.ManagerDepartment;
                else
                    userRoles = userRoles | Roles.ManagerEmployee;
            }
            else
            {
                userRoles = userRoles | Roles.Ess;
            }
            return userRoles;
        }
 public User(string username, string password, Roles role)
 {
     Username = username;
     PasswordHash = password;
     Role = role;
     Bookings = new List<Booking>();
 }
Esempio n. 7
0
 public TGrupo(string nombre, bool habilitado, Roles role)
 {
     this.Nombre = nombre;
     this.Habilitado = habilitado;
     this.Role = role;
     this.Descripcion = string.Empty;
 }
        public bool TryGetRoleCard(Roles currentRole, out RoleCard roleCard)
        {
            // TODO: add find with max money
            roleCard  = _status.RoleCards.FirstOrDefault(x => x.Role == currentRole && !x.IsUsed);

            return roleCard != null;
        }
Esempio n. 9
0
        public OnlyAllowAttribute(Roles roles)
        {
            if (roles == Roles.None)
                throw new ArgumentOutOfRangeException("roles");

            Roles = roles;
        }
Esempio n. 10
0
 public Player(string name, int number, Teams team, Roles role)
 {
     _name = name.Replace(" ", "");
     Number = number;
     Team = team;
     Role = role;
 }
        public PaginatedList<Article> ListPublishedArticles(int pageIndex = 0, int pageSize = 10, Roles role = Roles.None, string[] tags = null)
        {
            var tagsForbiddenForRole = this._RoleTagsBindingRepository.ListTagsForbiddenForRole(role);

            this._Logger.Debug("ListPublishedArticles: role = " + role);
            this._Logger.Debug("ListPublishedArticles: tags forbidden for role = " + string.Join(", ", tagsForbiddenForRole));

            var query =
                // We want all the enabled events
                (from @event in this._ArticleRepository.QueryPublished(tags)
                 select @event);

            // If our user is not an administrator
            if(role != Roles.Administrator)
            {
                query =
                    (from article in query
                    // Filter: all events without any tags
                 	where (!article.Tags.Any ())
                    // Or: @events who have all their tags bound to this role
                 	|| (!article.Tags.ContainsAny(tagsForbiddenForRole))
                    select article);
            }

            var result = query
                .OrderByDescending (article => article.PublicationDate)
                .ToPaginatedList (pageIndex, pageSize);

            return result;
        }
Esempio n. 12
0
 public TGrupo() {
     Id = 0;
     Nombre = string.Empty;
     Habilitado = false;
     _Roles = new Roles();
     this.Descripcion = string.Empty;
 }
Esempio n. 13
0
 public MetaData(Roles role, Actions action, ContentTypes contentType, string message)
 {
     this.role = role;
     this.action = action;
     this.contentType = contentType;
     messageSize = encoding.GetByteCount(message);
 }
Esempio n. 14
0
        public AlsoAllowAttribute(Roles roles)
        {
            if (roles == Roles.None)
                throw new ArgumentOutOfRangeException(nameof(roles));

            Roles = roles;
        }
Esempio n. 15
0
 public UserEditViewModel(string name, string mail, Roles role = Roles.User)
 {
     Name = name;
     Mail = mail;
     Role = role;
     GroupId = Resolver.GetInstance<IGroupsManager>().GetByName("Global").Id;
 }
Esempio n. 16
0
        public void AddRole(Roles role)
        {
            if (RoleExists(role))
                throw new ArgumentException(TooManyRole);

            entities.Roles.AddObject(role);
        }
Esempio n. 17
0
        public string GetDescription(Roles roleValue)
        {
            var dictionary = this.RolesToDescriptionManager.EnumToDescription;

            Debug.Assert(dictionary.ContainsKey(roleValue));

            return dictionary[roleValue];
        }
Esempio n. 18
0
 //public static bool UserIsSuperAdmin(this HttpContext ctx) {
 //    if (!ctx.User.Identity.IsAuthenticated) {
 //        return false;
 //    }
 //    var user = ctx.ActiveUserComplete();
 //    return user != null && user.IsSuperAdmin();
 //}
 // **************************************
 // UserIsInRole
 // **************************************
 public static bool UserIsInRole(this IPrincipal princ, Roles role)
 {
     if (!princ.Identity.IsAuthenticated) {
         return false;
     }
     var user = SessionService.Session().User(princ.Identity.Name);
     return user != null && user.IsInRole(role);
 }
Esempio n. 19
0
 public static void RedirectToWelcomeIfNotInRole(Roles role)
 {
     var user = Users.Current;
     if (!Users.IsInRole(user, role))
     {
         HttpContext.Current.Response.Redirect(user.HomePage);
     }
 }
Esempio n. 20
0
 public static bool createRole(Roles role)
 {
     using (DataClassesEduDataContext dc = new DataClassesEduDataContext())
     {
         dc.Roles.InsertOnSubmit(role);
         dc.SubmitChanges();
         return true;
     }
 }
        public void InitFilter(ServiceConfigParameters ServiceConfigParameters, RuntimeProperties RuntimeProperties, Roles Role, int SelfUserID)
        {
            RuntimeProperties.SetRuleValue(this.RoleContext.ToString(), RuntimeProperties.UserGroup.PropertyName);

            CountryCodeIncludingFilterParameter countrycodeparam = new CountryCodeIncludingFilterParameter();
            countrycodeparam.Filter = this.GetUserRoleFilter(ServiceConfigParameters, RuntimeProperties, Role);
            countrycodeparam.DefaultSeparator = Constants.DEFAULT_SEPARATOR;
            _CountryCodeIncludingFilter = new CountryCodeIncludingFilter(countrycodeparam);
        }
Esempio n. 22
0
        public void AddRole(string roleName)
        {
            var role = new Roles()
            {
                RoleName = roleName
            };

            AddRole(role);
        }
Esempio n. 23
0
 // Prepare LoginModel and get login result
 public LoginModel PrepareLoginModel(string Fullname, string Login, Roles Role)
 {
     LoginModel loginModel = new LoginModel()
     { 
         Fullname = Fullname,
         Role = Role,
         Login = Login
     };
     return loginModel;
 }
Esempio n. 24
0
 public ActionResult Edit(Roles roles)
 {
     if (ModelState.IsValid)
     {
         db.Entry(roles).State = EntityState.Modified;
         db.SaveChanges();
         return RedirectToAction("Index");
     }
     return View(roles);
 }
Esempio n. 25
0
        public void WhenInstantiatingClassWithDefaultConstructor_Succeeds()
        {
            // Arrange
            Roles model;

            // Act
            model = new Roles();

            // Assert
            Assert.NotNull(model);
        }
Esempio n. 26
0
        public ActionResult Create(Roles roles)
        {
            if (ModelState.IsValid)
            {
                db.Roles.Add(roles);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(roles);
        }
Esempio n. 27
0
 private void GetCurrentRole()
 {
     if (AuthorizeRole(Roles.Admin))
         _currentRole = Roles.Admin;
     else if (AuthorizeRole(Roles.ManagerDepartment))
         _currentRole = Roles.ManagerDepartment;
     else if (AuthorizeRole(Roles.ManagerEmployee))
         _currentRole = Roles.ManagerEmployee;
     else
         _currentRole = Roles.Ess;
 }
Esempio n. 28
0
 /// <summary>
 /// Decides if the user has a custom dashboard, or they are using default.
 /// </summary>
 /// <param name="user"></param>
 /// <param name="role"></param>
 /// <returns>Company or User</returns>
 public string GetDashboardType(User user, Roles role)
 {
     if (role == (Roles)1)
     {
         return "Company";
     }
     else
     {
         return "User";
     }
 }
Esempio n. 29
0
        public static string Add(string Path, string UserName, Roles Role)
        {
            try
            {
                DirectoryInfo dirinfo = new DirectoryInfo(Path);

                //ȡ�÷��ʿ����б�
                DirectorySecurity sec = dirinfo.GetAccessControl();
                switch (Role)
                {
                    case Roles.FullControl:
                        sec.AddAccessRule(new FileSystemAccessRule(UserName, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                        break;
                    case Roles.Read:
                        sec.AddAccessRule(new FileSystemAccessRule(UserName, FileSystemRights.Read, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                        break;
                    case Roles.Write:
                        sec.AddAccessRule(new FileSystemAccessRule(UserName, FileSystemRights.Write, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                        break;
                    case Roles.Modify:
                        sec.AddAccessRule(new FileSystemAccessRule(UserName, FileSystemRights.Modify, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                        break;
                }

                dirinfo.SetAccessControl(sec);
                return "OK";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            //����

            //    * path Ҫ���� NTFS Ȩ�޵��ļ��С�
            //    * identity �û�����
            //    * rights FileSystemRights ����ֵΪ FileSystemRights.Read��FileSystemRights.Write��FileSystemRights.FullControl �ȣ������á�|�������Ȩ�޺�������

            //InheritanceFlags ָ����Щ����Ȩ�޼̳�

            //    * InheritanceFlags.ContainerInherit �¼��ļ���Ҫ�̳�Ȩ�ޡ�
            //    * InheritanceFlags.None �¼��ļ��С��ļ������̳�Ȩ�ޡ�
            //    * InheritanceFlags.ObjectInherit �¼��ļ�Ҫ�̳�Ȩ�ޡ�

            //�����ᵽ���ļ��С������ļ�������׼ȷ��˵��Ӧ���ǡ�����������Ҷ���󡱣���Ϊ�������������ļ��С��ļ������������������ط�������ע���Ȩ�ޡ�

            //PropagationFlags ��δ���Ȩ��

            //    * PropagationFlags.InheritOnly ���� path �����ã�ֻ�Ǵ������¼���
            //    * PropagationFlags.None �������ã����ȶ� path �����ã�Ҳ�������¼���
            //    * PropagationFlags.NoPropagateInherit ֻ�Ƕ� path �����ã����������¼���

            //PropagationFlags ֻ���� InheritanceFlags ��Ϊ None ʱ�������塣Ҳ����˵ InheritanceFlags ָ�����������ɽ���Ȩ�޼̳У����������� PropagationFlags ָ������δ�����ЩȨ�ޡ�
        }
Esempio n. 30
0
 public Form1()
 {
     InitializeComponent();
     Role = new List<Roles>();
     ball = new Ball();
     ran = new Random();
     Role.Add(裁判一號 = new Roles(ball, "裁判一號", false));
     Role.Add(裁判二號 = new Roles(ball, "裁判二號", false));
     Role.Add(球迷一號 = new Roles(ball, "球迷一號", true));
     Role.Add(球迷二號 = new Roles(ball, "球迷二號", true));
 }
 public Roles Add(Roles entity)
 {
     throw new NotImplementedException();
 }
Esempio n. 32
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            Page.Title = SiteMapLocalizations.FAQPageTitle;
            editorCSS.Attributes.Add("href", "/css/" + Page.Theme + "/editor.css");
            shTheme.Attributes.Add("href", "/css/" + Page.Theme + "/shThemeDefault.css");
            if (webResources.TextDirection == "rtl")
            {
                faqCSS.Attributes.Add("href", "/css/" + Page.Theme + "/faqrtl.css");
            }
            else
            {
                faqCSS.Attributes.Add("href", "/css/" + Page.Theme + "/faq.css");
            }
            addTopic.Visible   = IsAuthenticated && (IsAdministrator || IsModerator || Roles.IsUserInRole("FaqAdmin"));
            manageCats.Visible = IsAuthenticated && (IsAdministrator || IsModerator || Roles.IsUserInRole("FaqAdmin"));
            if (!IsPostBack)
            {
                BindFaqNav();
            }
        }
 /// <summary>
 /// 修改
 /// </summary>
 /// <param name="roles"></param>
 /// <returns></returns>
 public int EditRoles(Roles roles)
 {
     return(rm.EditRoles(roles));
 }
Esempio n. 34
0
 public ActionResult CreateRole(string roleName)
 {
     Roles.CreateRole(roleName);
     return(View());
 }
Esempio n. 35
0
 private void A_Cluster_of_5_nodes_must_reach_initial_convergence()
 {
     AwaitClusterUp(Roles.ToArray());
     EnterBarrier("after-1");
 }
Esempio n. 36
0
 public RolesTests()
 {
     roles_0 = Roles.Empty.Add(firstRole);
 }
Esempio n. 37
0
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            //indicates whether the user is being approved.
            bool isInitialApproval = false;

            //if start page id isn't valid, 'WebModules_Pages_CheckPermission' sproc will fail.
            //if page id is null, user has access to all pages.
            int startPageId = (PagePicker.SelectedNavigationId == -1)
                ? Webpage.RootNavigationId
                : PagePicker.SelectedNavigationId;

            List <string> grantedRoles = new List <string>();

            string[] roles = Roles.GetRolesForUser(_user.UserName);

            foreach (ListItem li in RolesList.Items)
            {
                if (li.Selected)
                {
                    grantedRoles.Add(li.Value);
                }
            }

            if (roles.Length > 0)
            {
                Roles.RemoveUserFromRoles(_user.UserName, roles);
            }

            if (grantedRoles.Count > 0)
            {
                Roles.AddUserToRoles(_user.UserName, grantedRoles.ToArray());
            }

            _user.Email   = EmailCtl.Text;
            _user.Comment = CommentsCtl.Text;

            isInitialApproval =
                //was the user not approved yet?
                !_user.IsApproved
                //is the user being approved with this update?
                && IsApprovedCheckBox.Checked;

            _user.IsApproved = IsApprovedCheckBox.Checked;

            Membership.UpdateUser(_user);

            WebModulesProfile profile = WebModulesProfile.GetProfile(_user.UserName);

            if (null == profile)
            {
                profile = WebModulesProfile.Create(_user.UserName, true);
            }
            if (profile != null)
            {
                profile.FirstName   = FirstNameCtl.Text;
                profile.LastName    = LastNameCtl.Text;
                profile.StartPageId = startPageId;
                profile.Save();
            }

            if (isInitialApproval)
            { //notify the user that s/he has been approved.
                if (!string.IsNullOrEmpty(_user.Email))
                {
                    //this also resets the user's password.
                    securityModule.Model.SecurityEmail.NotifyUserOfApproval(_user);
                }
            }

            Response.Redirect("UserList.aspx");
        }
Esempio n. 38
0
 public bool IsInRole(string role)
 {
     return(Roles.Any(r => r.Contains(role)));
 }
Esempio n. 39
0
 public bool InRole(string role) => Roles.Any(ro => ro == role);
Esempio n. 40
0
 public ActionResult AddUserRole(string user)
 {
     Roles.AddUserToRole(user, "Admin");
     return(View("Index"));
 }
Esempio n. 41
0
 public RolesDAL(Roles Ra)
 {
     _Roles = Ra;
 }
 public bool IsInRole(string role)
 {
     return(Roles.IsUserInRole(role));
 }
Esempio n. 43
0
 public RolesDAL(int Id)
 {
     Db     = new SOKNAEntities();
     _Roles = Db.Roles.Single(r => r.Id == Id);
 }
Esempio n. 44
0
        public void Seed()
        {
            // Add the tokens
            var fanArt = ApplicationConfigurations.FirstOrDefault(x => x.Type == ConfigurationTypes.FanartTv);

            if (fanArt == null)
            {
                ApplicationConfigurations.Add(new ApplicationConfiguration
                {
                    Type  = ConfigurationTypes.FanartTv,
                    Value = "4b6d983efa54d8f45c68432521335f15"
                });
                SaveChanges();
            }
            var movieDb = ApplicationConfigurations.FirstOrDefault(x => x.Type == ConfigurationTypes.FanartTv);

            if (movieDb == null)
            {
                ApplicationConfigurations.Add(new ApplicationConfiguration
                {
                    Type  = ConfigurationTypes.TheMovieDb,
                    Value = "b8eabaf5608b88d0298aa189dd90bf00"
                });
                SaveChanges();
            }
            var notification = ApplicationConfigurations.FirstOrDefault(x => x.Type == ConfigurationTypes.Notification);

            if (notification == null)
            {
                ApplicationConfigurations.Add(new ApplicationConfiguration
                {
                    Type  = ConfigurationTypes.Notification,
                    Value = "4f0260c4-9c3d-41ab-8d68-27cb5a593f0e"
                });
                SaveChanges();
            }

            // VACUUM;
            Database.ExecuteSqlCommand("VACUUM;");

            // Make sure we have the roles
            var roles = Roles.Where(x => x.Name == OmbiRoles.RecievesNewsletter);

            if (!roles.Any())
            {
                Roles.Add(new IdentityRole(OmbiRoles.RecievesNewsletter)
                {
                    NormalizedName = OmbiRoles.RecievesNewsletter.ToUpper()
                });
            }
            //Check if templates exist
            var templates = NotificationTemplates.ToList();

            var allAgents = Enum.GetValues(typeof(NotificationAgent)).Cast <NotificationAgent>().ToList();
            var allTypes  = Enum.GetValues(typeof(NotificationType)).Cast <NotificationType>().ToList();

            foreach (var agent in allAgents)
            {
                foreach (var notificationType in allTypes)
                {
                    if (templates.Any(x => x.Agent == agent && x.NotificationType == notificationType))
                    {
                        // We already have this
                        continue;
                    }
                    NotificationTemplates notificationToAdd;
                    switch (notificationType)
                    {
                    case NotificationType.NewRequest:
                        notificationToAdd = new NotificationTemplates
                        {
                            NotificationType = notificationType,
                            Message          = "Hello! The user '{UserName}' has requested the {Type} '{Title}'! Please log in to approve this request. Request Date: {RequestedDate}",
                            Subject          = "{ApplicationName}: New {Type} request for {Title}!",
                            Agent            = agent,
                            Enabled          = true,
                        };
                        break;

                    case NotificationType.Issue:
                        notificationToAdd = new NotificationTemplates
                        {
                            NotificationType = notificationType,
                            Message          = "Hello! The user '{UserName}' has reported a new issue for the title {Title}! </br> {IssueCategory} - {IssueSubject} : {IssueDescription}",
                            Subject          = "{ApplicationName}: New issue for {Title}!",
                            Agent            = agent,
                            Enabled          = true,
                        };
                        break;

                    case NotificationType.RequestAvailable:
                        notificationToAdd = new NotificationTemplates
                        {
                            NotificationType = notificationType,
                            Message          = "Hello! You   {Title} on {ApplicationName}! This is now available! :)",
                            Subject          = "{ApplicationName}: {Title} is now available!",
                            Agent            = agent,
                            Enabled          = true,
                        };
                        break;

                    case NotificationType.RequestApproved:
                        notificationToAdd = new NotificationTemplates
                        {
                            NotificationType = notificationType,
                            Message          = "Hello! Your request for {Title} has been approved!",
                            Subject          = "{ApplicationName}: your request has been approved",
                            Agent            = agent,
                            Enabled          = true,
                        };
                        break;

                    case NotificationType.Test:
                        continue;

                    case NotificationType.RequestDeclined:
                        notificationToAdd = new NotificationTemplates
                        {
                            NotificationType = notificationType,
                            Message          = "Hello! Your request for {Title} has been declined, Sorry!",
                            Subject          = "{ApplicationName}: your request has been declined",
                            Agent            = agent,
                            Enabled          = true,
                        };
                        break;

                    case NotificationType.ItemAddedToFaultQueue:
                        continue;

                    case NotificationType.WelcomeEmail:
                        notificationToAdd = new NotificationTemplates
                        {
                            NotificationType = notificationType,
                            Message          = "Hello! You have been invited to use {ApplicationName}! You can login here: {ApplicationUrl}",
                            Subject          = "Invite to {ApplicationName}",
                            Agent            = agent,
                            Enabled          = true,
                        };
                        break;

                    case NotificationType.IssueResolved:
                        notificationToAdd = new NotificationTemplates
                        {
                            NotificationType = notificationType,
                            Message          = "Hello {UserName} Your issue for {Title} has now been resolved.",
                            Subject          = "{ApplicationName}: Issue has been resolved for {Title}!",
                            Agent            = agent,
                            Enabled          = true,
                        };
                        break;

                    case NotificationType.IssueComment:
                        notificationToAdd = new NotificationTemplates
                        {
                            NotificationType = notificationType,
                            Message          = "Hello, There is a new comment on your issue {IssueSubject}, The comment is: {NewIssueComment}",
                            Subject          = "{ApplicationName}: New comment on issue {IssueSubject}!",
                            Agent            = agent,
                            Enabled          = true,
                        };
                        break;

                    case NotificationType.AdminNote:
                        continue;

                    case NotificationType.Newsletter:
                        notificationToAdd = new NotificationTemplates
                        {
                            NotificationType = notificationType,
                            Message          = "Here is a list of Movies and TV Shows that have recently been added!",
                            Subject          = "{ApplicationName}: Recently Added Content!",
                            Agent            = agent,
                            Enabled          = true,
                        };
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                    NotificationTemplates.Add(notificationToAdd);
                }
            }
            SaveChanges();
        }
Esempio n. 45
0
 public RolesDAL()
 {
     _Roles = new Roles();
 }
Esempio n. 46
0
        /// <summary>
        /// Returns true if User instances are equal
        /// </summary>
        /// <param name="other">Instance of User to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(User other)
        {
            if (other is null)
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Uuid == other.Uuid ||
                     Uuid != null &&
                     Uuid.Equals(other.Uuid)
                     ) &&
                 (
                     Name == other.Name ||
                     Name != null &&
                     Name.Equals(other.Name)
                 ) &&
                 (
                     Surname == other.Surname ||
                     Surname != null &&
                     Surname.Equals(other.Surname)
                 ) &&
                 (
                     Username == other.Username ||
                     Username != null &&
                     Username.Equals(other.Username)
                 ) &&
                 (
                     Email == other.Email ||
                     Email != null &&
                     Email.Equals(other.Email)
                 ) &&
                 (
                     PhoneNumber == other.PhoneNumber ||
                     PhoneNumber != null &&
                     PhoneNumber.Equals(other.PhoneNumber)
                 ) &&
                 (
                     Avatar == other.Avatar ||
                     Avatar != null &&
                     Avatar.Equals(other.Avatar)
                 ) &&
                 (
                     IsDeleted == other.IsDeleted ||

                     IsDeleted.Equals(other.IsDeleted)
                 ) &&
                 (
                     LdapAuthenticationModeId == other.LdapAuthenticationModeId ||
                     LdapAuthenticationModeId != null &&
                     LdapAuthenticationModeId.Equals(other.LdapAuthenticationModeId)
                 ) &&
                 (
                     Roles == other.Roles ||
                     Roles != null &&
                     other.Roles != null &&
                     Roles.SequenceEqual(other.Roles)
                 ) &&
                 (
                     Teams == other.Teams ||
                     Teams != null &&
                     other.Teams != null &&
                     Teams.SequenceEqual(other.Teams)
                 ));
        }
Esempio n. 47
0
        public HttpResponseMessage Get([FromUri] string rol)
        {
            HttpResponseMessage httpResponse = new HttpResponseMessage();

            if (rol == "")
            {
                httpResponse = ManejoMensajes.RetornaMensajeParametroVacio(httpResponse, EnumMensajes.Parametro_vacio_o_invalido, "Rol Id");
            }
            else
            {
                string rolStr  = rol;
                bool   esSuper = false;
                if (rolStr == "Super Administrador")
                {
                    esSuper = true;
                }

                //ahora nos traemos a los usuarios de la entidad contratante o bien a todo si el rol es Super Administrador
                List <Usuarios>          userlist        = new List <Usuarios>();
                MembershipUserCollection listadeUsuarios = Membership.GetAllUsers();
                foreach (MembershipUser user in listadeUsuarios)
                {
                    //solo los de la app, ya que existen usuarios de vio salud aca
                    string[] rolesEvaluar = Roles.GetRolesForUser(user.UserName);
                    if (Roles.IsUserInRole(user.UserName, "Administrador Lun") ||
                        Roles.IsUserInRole(user.UserName, "Administrador Web") ||
                        Roles.IsUserInRole(user.UserName, "Consultador Lun") ||
                        Roles.IsUserInRole(user.UserName, "Super Administrador"))
                    {
                        Usuarios us    = new Usuarios();
                        string[] roles = Roles.GetRolesForUser(user.UserName);

                        us.Emmail        = user.Email;
                        us.NombreUsuario = user.UserName;
                        us.Aprobado      = user.IsApproved;
                        //******************************************
                        ProfileBase prof = ProfileBase.Create(user.UserName);

                        if (prof != null)
                        {
                            //asociar los elementos necesarios
                            us.EncoId          = (int)prof.GetPropertyValue("EncoId");
                            us.Rut             = (string)prof.GetPropertyValue("Rut");
                            us.Nombres         = (string)prof.GetPropertyValue("Nombres");
                            us.ApellidoPaterno = (string)prof.GetPropertyValue("ApellidoPaterno");
                            us.ApellidoMaterno = (string)prof.GetPropertyValue("ApellidoMaterno");
                            us.Direccion       = (string)prof.GetPropertyValue("Direccion");
                            us.RestoDireccion  = (string)prof.GetPropertyValue("RestoDireccion");
                            us.TelefonoFijo    = (string)prof.GetPropertyValue("TelefonoFijo");
                            us.TelefonoCelular = (string)prof.GetPropertyValue("TelefonoCelular");
                            us.Estamento       = (string)prof.GetPropertyValue("Estamento");
                            us.Contratante     = (string)prof.GetPropertyValue("Contratante");
                            us.IdRegion        = (int)prof.GetPropertyValue("IdRegion");
                            us.IdComuna        = (int)prof.GetPropertyValue("IdComuna");
                            us.VeReportes      = (bool)prof.GetPropertyValue("VeReportes");
                            us.NombreCompleto  = us.Nombres + " " + us.ApellidoPaterno + " " + us.ApellidoMaterno;
                        }
                        if (us.VeReportes)
                        {
                            us.VeReportesTexto = "Si";
                        }
                        else
                        {
                            us.VeReportesTexto = "No";
                        }
                        //obtención de la region
                        RayenSalud.WebLun.Entidad.Territorio.Region region = RayenSalud.WebLun.Negocio.Territorio.Territorio.ObtenerRegionPorId(us.IdRegion);
                        if (region != null)
                        {
                            us.NombreRegion = region.Nombre;
                        }
                        RayenSalud.WebLun.Entidad.Territorio.Comuna comuna = RayenSalud.WebLun.Negocio.Territorio.Territorio.ObtenerComunaPorId(us.IdComuna);
                        if (comuna != null)
                        {
                            us.NombreComuna = comuna.Nombre;
                        }
                        RayenSalud.WebLun.Entidad.Global.ContratanteLun contratante = new RayenSalud.WebLun.Entidad.Global.ContratanteLun();
                        //obtenemos el contratante por el nombre
                        if (us.EncoId > 0)
                        {
                            contratante = RayenSalud.WebLun.Negocio.Global.Global.ObtenerContratanteLunPorId(us.EncoId);
                        }

                        if (contratante != null)
                        {
                            us.Contratante = contratante.RazonSocial;
                        }

                        us.RolesUsuarios = roles;
                        if (roles != null)
                        {
                            if (roles.Length > 0)
                            {
                                us.RolUsuario = roles[0];
                            }
                        }

                        userlist.Add(us);
                    }
                }
                //ACA EVALUAMOS
                if (userlist != null && userlist.Count > 0)
                {
                    if (!esSuper)
                    {
                        userlist = userlist.FindAll(p => p.RolUsuario != "Super Administrador");
                    }
                }
                httpResponse = ManejoMensajes.RetornaMensajeCorrecto(httpResponse, userlist);
            }

            return(httpResponse);
        }
 public void update(Roles entity)
 {
     throw new NotImplementedException();
 }
Esempio n. 49
0
        public IHttpActionResult EmployeeRegister(Individual model)
        {
            try
            {
                if (model.fullName == null)
                {
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "224-Full name is required"), new JsonMediaTypeFormatter()));
                }
                else
                {
                    if (string.IsNullOrEmpty(model.fullName.Ar_SA) && string.IsNullOrEmpty(model.fullName.En_US))
                    {
                        return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "224-Full name is required"), new JsonMediaTypeFormatter()));
                    }
                }
                // Validate Model
                if (!ModelState.IsValid)
                {
                    var modelErrors = new List <string>();
                    foreach (var modelState in ModelState.Values)
                    {
                        foreach (var modelError in modelState.Errors)
                        {
                            modelErrors.Add(modelError.ErrorMessage == "" ? modelError.Exception.Message : modelError.ErrorMessage);
                        }
                    }
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), modelErrors[0].ToString()), new JsonMediaTypeFormatter()));
                }

                var userDocumentEmail = _bucket.Query <object>(@"SELECT * From " + _bucket.Name + " where email= '" + model.Email + "' and isActive=true").ToList();
                if (userDocumentEmail.Count > 0)
                {
                    return(Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), "105-The e-mail already exists"), new JsonMediaTypeFormatter()));
                }

                if (model.LoginDetails != null)
                {
                    if (string.IsNullOrEmpty(model.LoginDetails.Password))
                    {
                        return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "158-Password is required"), new JsonMediaTypeFormatter()));
                    }
                }

                var userDocumentPhone = _bucket.Query <object>(@"SELECT * From " + _bucket.Name + " where " + _bucket.Name + ".mobNum.num= '" + model.MobNum.NumM + "'").ToList();

                if (userDocumentPhone.Count > 0)
                {
                    return(Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), "Mobile number already exists"), new JsonMediaTypeFormatter()));
                }

                Address address = new Address();
                address.City    = model.Address.City;
                address.State   = model.Address.State;
                address.Area    = model.Address.Area;
                address.Street  = model.Address.Street;
                address.BldgNum = model.Address.BldgNum;
                address.FlatNum = model.Address.FlatNum;

                MobNum mobNum = new MobNum();
                mobNum.CountryCodeM = model.MobNum.CountryCodeM;
                mobNum.NumM         = model.MobNum.NumM;
                mobNum.AreaM        = model.MobNum.AreaM;

                TelNum telNum = new TelNum();
                if (model.TelNum != null)
                {
                    telNum.CountryCodeT = model.TelNum.CountryCodeT;
                    telNum.NumT         = model.TelNum.NumT;
                    telNum.AreaT        = model.TelNum.AreaT;
                }

                List <AuditInfo> lstauditInfo = new List <AuditInfo>();
                AuditInfo        auditInfo    = new AuditInfo();
                auditInfo.Version        = "1";
                auditInfo.Status         = "true";
                auditInfo.LastChangeDate = DataConversion.ConvertYMDHMS(DateTime.Now.ToString());
                auditInfo.LastChangeBy   = model.Email;
                lstauditInfo.Add(auditInfo);

                List <Roles> lstRoles = new List <Roles>();
                if (model.Roles != null)
                {
                    foreach (var role in model.Roles)
                    {
                        Roles roles = new Roles();
                        roles.RoleID = role.RoleID;
                        roles.Name   = role.Name;
                        roles.Link   = role.Link;
                        lstRoles.Add(roles);
                    }
                }

                #region MyRegion
                List <Fines>        lstFines        = new List <Fines>();
                List <Documents>    lstDocuments    = new List <Documents>();
                List <Vehicles>     lstVehicles     = new List <Vehicles>();
                List <Incidents>    lstIncident     = new List <Incidents>();
                List <ScoreCards>   lstScoreCard    = new List <ScoreCards>();
                List <DriverStatus> lstdriverStatus = new List <DriverStatus>();
                #endregion

                FullName fullName = new FullName();
                fullName.En_US = model.fullName.En_US;
                fullName.Ar_SA = model.fullName.Ar_SA;

                Status status = new Status();
                if (model.Status != null)
                {
                    status.StatusID = model.Status.StatusID;
                    status.DateTime = model.Status.DateTime;
                }



                //DataConversion.ConvertYMDHMS(DateTime.Now.AddDays(Convert.ToInt16(ConfigurationManager.AppSettings.Get("ValidToProfilePhotoDays"))).ToString())
                ProfilePhoto profilePhoto = new ProfilePhoto();
                if (model.ProfilePhoto != null)
                {
                    profilePhoto.DocFormat = model.ProfilePhoto.DocFormat;
                    profilePhoto.Photo     = model.ProfilePhoto.Photo;
                    profilePhoto.ValidFrom = DataConversion.ConvertYMDHMS(DateTime.Now.ToString());
                    profilePhoto.ValidTo   = DataConversion.ConvertYMDHMS(DateTime.Now.AddDays(Convert.ToInt16(ConfigurationManager.AppSettings.Get("ValidToProfilePhotoDays"))).ToString());
                }
                string docId = string.Empty;
                if (string.IsNullOrEmpty(model.KeyID))
                {
                    docId = "individual_" + Guid.NewGuid();
                }
                else
                {
                    docId = "individual_" + model.KeyID;
                }

                var employeeDoc = new Document <Individual>()
                {
                    Id      = docId,
                    Content = new Individual
                    {
                        KeyID         = docId,
                        fullName      = fullName,
                        DOB           = DataConversion.ConvertDateYMD(model.DOB),
                        Nationality   = model.Nationality,
                        Gender        = model.Gender,
                        Fines         = lstFines,
                        Language      = model.Language,
                        MaritalStatus = model.MaritalStatus,
                        MobNum        = mobNum,
                        AuditInfo     = lstauditInfo,
                        Vehicles      = lstVehicles,
                        Roles         = lstRoles,
                        TelNum        = telNum,
                        DocType       = ("Individual").ToLower(),
                        Documents     = lstDocuments,
                        Email         = model.Email,
                        ProfilePhoto  = profilePhoto,
                        Notes         = model.Notes,
                        ScoreCards    = lstScoreCard,
                        Address       = address,
                        Religion      = model.Religion,
                        Status        = status,
                        Incidents     = lstIncident,
                        DriverStatus  = lstdriverStatus,
                    },
                };
                var result = _bucket.Insert(employeeDoc);
                if (!result.Success)
                {
                    return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), result.Message), new JsonMediaTypeFormatter()));
                }
                return(Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(), MessageDescriptions.Add, result.Document.Id), new JsonMediaTypeFormatter()));
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.StackTrace), new JsonMediaTypeFormatter()));
            }
        }
Esempio n. 50
0
        public HttpResponseMessage Post(dynamic DynamicClass)
        {
            HttpResponseMessage httpResponse = new HttpResponseMessage();

            string Input = JsonConvert.SerializeObject(DynamicClass);

            dynamic data = JObject.Parse(Input);

            if (data.Usuario == "")
            {
                httpResponse = ManejoMensajes.RetornaMensajeParametroVacio(httpResponse, EnumMensajes.Parametro_vacio_o_invalido, "Usuario");
            }
            else if (data.Clave == "")
            {
                httpResponse = ManejoMensajes.RetornaMensajeParametroVacio(httpResponse, EnumMensajes.Parametro_vacio_o_invalido, "Clave");
            }
            else
            {
                try
                {
                    string           usuario = data.Usuario;
                    string           clave   = data.Clave;
                    Entidad.Usuarios us      = new Entidad.Usuarios();

                    bool correcto = Membership.ValidateUser(usuario, clave);
                    if (correcto)
                    {
                        //obtenemos al usuario
                        MembershipUser user = Membership.GetUser(usuario);
                        if (user != null)
                        {
                            //datos propios
                            us.Emmail        = user.Email;
                            us.NombreUsuario = user.UserName;
                            us.Aprobado      = user.IsApproved;
                            //******************************************
                            ProfileBase prof  = ProfileBase.Create(usuario);
                            string[]    roles = Roles.GetRolesForUser(usuario);
                            if (prof != null)
                            {
                                //asociar los elementos necesarios
                                us.EncoId          = (int)prof.GetPropertyValue("EncoId");
                                us.Rut             = (string)prof.GetPropertyValue("Rut");
                                us.Nombres         = (string)prof.GetPropertyValue("Nombres");
                                us.ApellidoPaterno = (string)prof.GetPropertyValue("ApellidoPaterno");
                                us.ApellidoMaterno = (string)prof.GetPropertyValue("ApellidoMaterno");
                                us.Direccion       = (string)prof.GetPropertyValue("Direccion");
                                us.RestoDireccion  = (string)prof.GetPropertyValue("RestoDireccion");
                                us.TelefonoFijo    = (string)prof.GetPropertyValue("TelefonoFijo");
                                us.TelefonoCelular = (string)prof.GetPropertyValue("TelefonoCelular");
                                us.Estamento       = (string)prof.GetPropertyValue("Estamento");
                                us.Contratante     = (string)prof.GetPropertyValue("Contratante");
                                us.IdRegion        = (int)prof.GetPropertyValue("IdRegion");
                                us.IdComuna        = (int)prof.GetPropertyValue("IdComuna");
                                us.VeReportes      = (bool)prof.GetPropertyValue("VeReportes");
                                us.NombreCompleto  = us.Nombres + " " + us.ApellidoPaterno + " " + us.ApellidoMaterno;
                            }
                            if (us.VeReportes)
                            {
                                us.VeReportesTexto = "Si";
                            }
                            else
                            {
                                us.VeReportesTexto = "No";
                            }
                            //obtención de la region
                            RayenSalud.WebLun.Entidad.Territorio.Region region = RayenSalud.WebLun.Negocio.Territorio.Territorio.ObtenerRegionPorId(us.IdRegion);
                            if (region != null)
                            {
                                us.NombreRegion = region.Nombre;
                            }
                            RayenSalud.WebLun.Entidad.Territorio.Comuna comuna = RayenSalud.WebLun.Negocio.Territorio.Territorio.ObtenerComunaPorId(us.IdComuna);
                            if (comuna != null)
                            {
                                us.NombreComuna = comuna.Nombre;
                            }
                            RayenSalud.WebLun.Entidad.Global.ContratanteLun contratante = new RayenSalud.WebLun.Entidad.Global.ContratanteLun();
                            //obtenemos el contratante por el nombre
                            if (us.EncoId > 0)
                            {
                                contratante = RayenSalud.WebLun.Negocio.Global.Global.ObtenerContratanteLunPorId(us.EncoId);
                            }

                            if (contratante != null)
                            {
                                us.Contratante = contratante.RazonSocial;
                            }

                            us.RolesUsuarios = roles;
                            if (roles != null)
                            {
                                if (roles.Length > 0)
                                {
                                    us.RolUsuario = roles[0];
                                }
                            }



                            httpResponse = ManejoMensajes.RetornaMensajeCorrecto(httpResponse, us);
                        }
                        else
                        {
                            httpResponse = ManejoMensajes.RetornaMensajeError(httpResponse, EnumMensajes.Usuario_no_existe);
                        }
                    }
                    else
                    {
                        httpResponse = ManejoMensajes.RetornaMensajeError(httpResponse, EnumMensajes.Clave_incorrecta);
                    }
                }
                catch (Exception ex)
                {
                    Negocio.Utiles.NLogs(ex);
                    httpResponse = ManejoMensajes.RetornaMensajeExcepcion(httpResponse, ex);
                }
            }
            return(httpResponse);
        }
Esempio n. 51
0
        public void UpdateUser(Account account, Guid modifyUserId)
        {
            MembershipUser user = Membership.GetUser(account.PrimaryEmail);

            if (user != null)
            {
                if (user.IsApproved != account.IsActive)
                {
                    if (!account.IsActive)
                    {
                        UmsMailing.Instance.SendBlockAccountMail(account.PrimaryEmail);
                    }
                    else
                    {
                        UmsMailing.Instance.SendUnlockAccountMail(account.PrimaryEmail);
                    }
                    user.IsApproved = account.IsActive;
                    Membership.UpdateUser(user);
                }
            }
            if (!Roles.IsUserInRole(account.PrimaryEmail, account.Role))
            {
                Roles.RemoveUserFromRoles(account.PrimaryEmail, Roles.GetRolesForUser(account.PrimaryEmail));
                Roles.AddUserToRole(account.PrimaryEmail, account.Role);
            }
            DateTime now = DateTime.Now;

            account.ModifyUserId = modifyUserId;
            account.ModifyDate   = now;
            foreach (FullAddress fullAddress in account.FullAddresses)
            {
                if (fullAddress.CreateUserId == Guid.Empty)
                {
                    fullAddress.CreateUserId = modifyUserId;
                    fullAddress.CreateDate   = now;
                }
                fullAddress.ModifyUserId = modifyUserId;
                fullAddress.ModifyDate   = now;
            }
            foreach (Phone phone in account.Phones)
            {
                if (phone.CreateUserId == Guid.Empty)
                {
                    phone.CreateUserId = modifyUserId;
                    phone.CreateDate   = now;
                }
                phone.ModifyUserId = modifyUserId;
                phone.ModifyDate   = now;
            }
            foreach (Email email in account.Emails)
            {
                if (email.CreateUserId == Guid.Empty)
                {
                    email.CreateUserId = modifyUserId;
                    email.CreateDate   = now;
                }
                email.ModifyUserId = modifyUserId;
                email.ModifyDate   = now;
            }
            this._accountDac.Save(account);
        }
Esempio n. 52
0
        public UserInfo Login(Credential credential)
        {
            // try to sign in
            if (WebSecurity.Login(credential.UserName, credential.Password, persistCookie: credential.RememberMe))
            {
                // Create a new Principal and return authenticated
                IPrincipal principal = new GenericPrincipal(new GenericIdentity(credential.UserName), Roles.GetRolesForUser(credential.UserName));
                Thread.CurrentPrincipal  = principal;
                HttpContext.Current.User = principal;
                return(new UserInfo
                {
                    IsAuthenticated = true,
                    UserName = credential.UserName,
                    Roles = Roles.GetRolesForUser(credential.UserName)
                });
            }
            // if you get here => return 401 Unauthorized
            var errors = new Dictionary <string, IEnumerable <string> >();

            errors.Add("Authorization", new string[] { "The supplied credentials are not valid" });
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized, errors));
        }
Esempio n. 53
0
        public MembershipCreateStatus SaveUser(Account account, Guid curentUserId)
        {
            MembershipCreateStatus membershipCreateStatu;
            MembershipCreateStatus membershipCreateStatu1;
            string         str          = Membership.GeneratePassword(12, 1);
            MembershipUser primaryEmail = Membership.CreateUser(account.PrimaryEmail, str, account.PrimaryEmail, null, null, account.IsActive, null, out membershipCreateStatu);

            if (membershipCreateStatu == MembershipCreateStatus.Success)
            {
                Roles.AddUserToRole(account.PrimaryEmail, account.Role);
                if (primaryEmail != null)
                {
                    if (primaryEmail.ProviderUserKey != null)
                    {
                        account.Id = (Guid)primaryEmail.ProviderUserKey;
                    }
                    primaryEmail.Email   = account.PrimaryEmail;
                    primaryEmail.Comment = "Redirect to change password";
                    Guid     guid  = curentUserId;
                    DateTime now   = DateTime.Now;
                    Guid     guid1 = guid;
                    Guid     guid2 = guid1;
                    account.ModifyUserId = guid1;
                    account.CreateUserId = guid2;
                    DateTime dateTime  = now;
                    DateTime dateTime1 = dateTime;
                    account.ModifyDate = dateTime;
                    account.CreateDate = dateTime1;
                    foreach (FullAddress fullAddress in account.FullAddresses)
                    {
                        DateTime dateTime2 = now;
                        dateTime1 = dateTime2;
                        fullAddress.ModifyDate = dateTime2;
                        fullAddress.CreateDate = dateTime1;
                        Guid guid3 = guid;
                        guid2 = guid3;
                        fullAddress.ModifyUserId = guid3;
                        fullAddress.CreateUserId = guid2;
                    }
                    foreach (Email email in account.Emails)
                    {
                        DateTime dateTime3 = now;
                        dateTime1        = dateTime3;
                        email.ModifyDate = dateTime3;
                        email.CreateDate = dateTime1;
                        Guid guid4 = guid;
                        guid2 = guid4;
                        email.ModifyUserId = guid4;
                        email.CreateUserId = guid2;
                    }
                    foreach (Phone phone in account.Phones)
                    {
                        DateTime dateTime4 = now;
                        dateTime1        = dateTime4;
                        phone.ModifyDate = dateTime4;
                        phone.CreateDate = dateTime1;
                        Guid guid5 = guid;
                        guid2 = guid5;
                        phone.ModifyUserId = guid5;
                        phone.CreateUserId = guid2;
                    }
                    Membership.UpdateUser(primaryEmail);
                    this._accountDac.Save(account);
                    UmsMailing.Instance.SendSuccessRegistrationMail(account.PrimaryEmail, account.FirstName, account.LastName, account.PrimaryEmail, str);
                }
                membershipCreateStatu1 = membershipCreateStatu;
            }
            else
            {
                membershipCreateStatu1 = membershipCreateStatu;
            }
            return(membershipCreateStatu1);
        }
Esempio n. 54
0
 public UserInfo Register(RegisterModel model)
 {
     try
     {
         WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email });
         WebSecurity.Login(model.UserName, model.Password);
         Roles.AddUsersToRole(new string[] { model.UserName }, Settings.Default.DefaultRole);
         IPrincipal principal = new GenericPrincipal(new GenericIdentity(model.UserName), Roles.GetRolesForUser(model.UserName));
         Thread.CurrentPrincipal  = principal;
         HttpContext.Current.User = principal;
         return(new UserInfo()
         {
             IsAuthenticated = true,
             UserName = model.UserName,
             Roles = new List <string> {
                 Settings.Default.DefaultRole
             }
         });
     }
     catch (MembershipCreateUserException e)
     {
         throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, e.Message));
     }
 }
 /// <summary>
 /// 新增
 /// </summary>
 /// <param name="roles"></param>
 /// <returns></returns>
 public int AddRoles(Roles roles)
 {
     return(rm.AddRoles(roles));
 }
Esempio n. 56
0
 public AuthorizeEnumAttribute(Roles roles)
 {
     Roles = roles.ToString();
 }
Esempio n. 57
0
 /// <summary>
 /// Obtiene un Operador que es Usuario
 /// </summary>
 /// <param name="usuarioId"></param>
 /// <param name="organizacionId"> </param>
 /// <param name="basculista"></param>
 /// <returns></returns>
 internal OperadorInfo ObtenerPorUsuarioIdRol(int usuarioId, int organizacionId, Roles basculista)
 {
     try
     {
         Logger.Info();
         var          operadorDAL = new OperadorDAL();
         OperadorInfo result      = operadorDAL.ObtenerPorUsuarioIdRol(usuarioId, organizacionId, basculista);
         return(result);
     }
     catch (ExcepcionGenerica)
     {
         throw;
     }
     catch (Exception ex)
     {
         Logger.Error(ex);
         throw new ExcepcionDesconocida(MethodBase.GetCurrentMethod(), ex);
     }
 }
Esempio n. 58
0
        static void Main(string[] args)
        {
            Salaries salaries = new Salaries();

            salaries.Add(new Salarie()
            {
                Matricule     = "23ABC56",
                Nom           = "Bost",
                Prenom        = "Vincent",
                DateNaissance = new DateTime(1962, 01, 13),
                SalaireBrut   = 3500,
                TauxCS        = 0.25M
            });
            salaries.Add(new Salarie()
            {
                Matricule     = "23ABC50",
                Nom           = "Morillon",
                Prenom        = "Jean",
                DateNaissance = new DateTime(1959, 10, 13),
                SalaireBrut   = 3500,
                TauxCS        = 0.25M
            });
            salaries.Add(new Commercial()
            {
                Matricule      = "23ABC51",
                Nom            = "Goddaert",
                Prenom         = "Elisbeth",
                DateNaissance  = new DateTime(1963, 6, 05),
                SalaireBrut    = 3500,
                TauxCS         = 0.25M,
                ChiffreAffaire = 1500,
                Commission     = 10
            });
            ISauvegarde sauvegarde = new SauvegardeXML();

            salaries.Save(sauvegarde, Settings.Default.AppData);

            Roles roles = new Roles();

            roles.Add(new Role()
            {
                Identifiant = "Utilisateur", Description = "Utilisateur Application"
            });
            roles.Add(new Role()
            {
                Identifiant = "Administrateur", Description = "Administrateur Application"
            });
            roles.Save(sauvegarde, Settings.Default.AppData);
            Utilisateur utilisateur = new Utilisateur()
            {
                Identifiant = "C6GB011", MotDePasse = "Vince1962", Nom = "Bost", CompteBloque = false, Role = roles.ElementAt(1)
            };


            Utilisateurs utilisateurs = new Utilisateurs();

            utilisateurs.Add(utilisateur);
            utilisateur = new Utilisateur()
            {
                Identifiant = "A7DC011", MotDePasse = "Jean1959", Nom = "Morillon", CompteBloque = false, Role = roles.ElementAt(0)
            };
            utilisateurs.Add(utilisateur);
            utilisateurs.Save(sauvegarde, Settings.Default.AppData);
            Console.WriteLine(roles.RechercherRole("Administrateur").ToString());
            Console.ReadLine();
        }
        public Roles New(Roles entity)
        {
            RolesBo RolesBo = new RolesBo();

            return(RolesBo.Insert(entity));
        }
        public Roles Update(Roles entity)
        {
            RolesBo RolesBo = new RolesBo();

            return(RolesBo.Update(entity));
        }