public HAMSPrinciple(int ID)
        {
            moduleSettings = WebModules.Configuration.ModuleConfig.GetSettings();

            Data.Engineer dataUser = new Data.Engineer (moduleSettings);
            identity = new HAMSIdentity(ID);
        }
        /// <summary>
        /// 根据用户编号构造
        /// </summary>
        public AccountsPrincipal(int userID)
		{				
			identity = new SiteIdentity(userID);
			permissionList = dataUser.GetEffectivePermissionList(userID);
			permissionListid=dataUser.GetEffectivePermissionListID(userID);
			roleList = dataUser.GetUserRoles(userID);
		}
        /// <summary>
        /// 根据用户名构造
        /// </summary>
		public AccountsPrincipal(string userName)
		{		
			identity = new SiteIdentity(userName);
			permissionList = dataUser.GetEffectivePermissionList( ((SiteIdentity)identity).UserID );
			permissionListid=dataUser.GetEffectivePermissionListID(((SiteIdentity)identity).UserID);
			roleList = dataUser.GetUserRoles(((SiteIdentity)identity).UserID );
		}
        public WebPrinciple(string userName)
        {
            moduleSettings = ModuleConfig.GetSettings();

            Data.User user = new Data.User(moduleSettings);
            identity = new SiteIdentity(userName);
        }
示例#5
0
 public ListenToUser(MembershipUser membershipUser, IUserManager userManager)
 {
     this._membershipUser = membershipUser;
     Guid id = (Guid)this._membershipUser.ProviderUserKey;
     _user = userManager.GetByID(id);
     _identity = new System.Security.Principal.GenericIdentity(this._membershipUser.UserName);
     _userCredentials = new UserCredentials();
     _userCredentials.Username = _user.Username;
     _userCredentials.Password = _user.Password;
 }
示例#6
0
 public static ApplicationUser GetApplicationUser(this System.Security.Principal.IIdentity identity)
 {
     if (identity.IsAuthenticated)
     {
         using (var db = new CinemaContext())
         {
             var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(db));
             return(userManager.FindByName(identity.Name));
         }
     }
     else
     {
         return(null);
     }
 }
示例#7
0
        public void Create(HttpPostedFileBase src, Blog create, System.Security.Principal.IIdentity identity)
        {
            create.CreateTime = DateTime.Now;
            create.UserName   = Microsoft.AspNet.Identity.IdentityExtensions.GetUserName(identity);
            if (src != null)
            {
                // получаем имя файла
                string fileName = System.IO.Path.GetFileName(src.FileName);
                //сохраняем файл в папку Files в проекте
                src.SaveAs(HttpContext.Current.Server.MapPath(@"~\Images\" + fileName));
                create.ImagePath = @"~\Images\" + fileName;
            }

            context.Blogs.Add(create);
        }
示例#8
0
        public static int GetUserTypeFromToken(System.Security.Principal.IIdentity pIdentity)
        {
            var loUserType = -1;

            if (!(pIdentity is ClaimsIdentity identity))
            {
                return(loUserType);
            }

            var loTemp = identity.Claims.FirstOrDefault(x => x.Type.ToLower().Contains("gender"))?.Value;

            if (!int.TryParse(loTemp, out loUserType))
            {
                loUserType = -1;
            }
            return(loUserType);
        }
示例#9
0
 public MyPrincipal(string userID, string password)
 {
     //
     // TODO: 在此处添加构造函数逻辑
     //
     identity = new MyIdentity(userID, password);
     if (identity.IsAuthenticated)
     {
         //如果通过验证则获取该用户的Role,这里可以修改为从数据库中
         //读取指定用户的Role并将其添加到Role中,本例中直接为用户添加一个Admin角色
         roleList = new ArrayList();
         roleList.Add("Admin");
     }
     else
     {
         // do nothing
     }
 }
示例#10
0
 public BizMessage(System.Security.Principal.IIdentity Identity)
 {
     try
     {
         MsgData = new Dictionary <string, string>();
         var identity = Identity as System.Security.Claims.ClaimsIdentity;
         if (identity != null)
         {
             this.Headers = new NameValueCollection();
             foreach (System.Security.Claims.Claim claim in identity.Claims)
             {
                 this.Headers.Add(claim.Type.ToString(), claim.Value.ToString());
             }
         }
     }
     catch (Exception ex)
     {
     }
 }
示例#11
0
        public static string getUserID(System.Security.Principal.IIdentity ident)
        {
            var claimIdent = ident as ClaimsIdentity;

            if (claimIdent != null)
            {
                var userIdClaim = claimIdent.Claims.FirstOrDefault(u => u.Type == ClaimTypes.NameIdentifier);

                if (userIdClaim != null)
                {
                    return(userIdClaim.Value);
                }
                return("none");
            }
            else
            {
                return("none");
            }
        }
示例#12
0
        public static string GetProfileUrl(this System.Security.Principal.IIdentity identity)
        {
            ClaimsIdentity claimIdentity = identity as ClaimsIdentity;

            if (claimIdentity == null)
            {
                return(string.Empty);
            }

            if (claimIdentity.AuthenticationType == GoogleDefaults.DisplayName)
            {
                var claim = claimIdentity.FindFirst("urn:google:profile");
                if (claim != null)
                {
                    return(claim.Value);
                }
            }

            return(string.Empty);
        }
示例#13
0
        /// <summary>
        /// Generates dummy data for the prototype if it has not already been generated
        /// </summary>
        public static void GenerateDummyData()
        {
            if (!m_bHasDummyDataBeenGenerated)
            {
                //add the logged in user
                AllUsers = new List <User>();
                System.Security.Principal.IIdentity usr = System.Security.Principal.WindowsIdentity.GetCurrent();
                AllUsers.Add(new User {
                    UserId = Guid.NewGuid(), UserName = usr.Name, DisplayName = usr.Name
                });


                //instanciate time entries
                AllTimeEntries         = new List <TimeEntry>();
                AllTimeEntryExceptions = new List <TimeEntryException>();


                //set it to true as it has now been done
                m_bHasDummyDataBeenGenerated = true;
            }
        }
示例#14
0
        /// <summary>
        /// 根据用户编号构造
        /// </summary>
        public AccountsPrincipal(int userID)
        {
            identity = new SiteIdentity(userID);

            #region 数据库权限

            permissionLists = dataUser.GetEffectivePermissionLists(userID);
            if (permissionLists.Tables.Count > 0)
            {
                foreach (DataRow dr in permissionLists.Tables[0].Rows)
                {
                    permissionListid.Add(Convert.ToInt32(dr["PermissionID"]));
                    permissionsDesc.Add(dr["Description"].ToString());
                    //增加用户 的特别权限
                }
            }

            #endregion

            rolesKeyValue = dataUser.GetUserRoles4KeyValues(userID);
        }
示例#15
0
 public static bool ValidateSecurityStamp(this System.Security.Principal.IIdentity identity, string stamp)
 {
     if (identity.IsAuthenticated)
     {
         var store       = new UserStore <ApplicationUser>(new ApplicationDbContext());
         var userManager = new ApplicationUserManager(store);
         var user        = userManager.FindById(identity.GetUserId());
         if (user != null)
         {
             if (user.SecurityStamp == stamp)
             {
                 return(true);
             }
         }
         return(false);
     }
     else
     {
         return(false);
     }
 }
示例#16
0
        /// <summary>
        /// 连接网络资源
        /// </summary>
        /// <param name="domain">IP/计算机名</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public static bool impersonateValidUser(String domain, String userName, String password)
        {
            System.Security.Principal.WindowsIdentity tempWindowsIdentity;
            IntPtr token          = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {
                // 这里使用LOGON32_LOGON_NEW_CREDENTIALS来访问远程资源。
                // 如果要(通过模拟用户获得权限)实现服务器程序,访问本地授权数据库可
                // 以用LOGON32_LOGON_INTERACTIVE
                if (LogonUser(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS,
                              LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity  = new System.Security.Principal.WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            System.AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
                            System.Security.Principal.IPrincipal pr = System.Threading.Thread.CurrentPrincipal;
                            System.Security.Principal.IIdentity  id = pr.Identity;
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return(true);
                        }
                    }
                }
            }
            if (token != IntPtr.Zero)
            {
                CloseHandle(token);
            }
            if (tokenDuplicate != IntPtr.Zero)
            {
                CloseHandle(tokenDuplicate);
            }
            return(false);
        }
示例#17
0
        public void Update(HttpPostedFileBase src, Blog update, System.Security.Principal.IIdentity identity)
        {
            var newBlog = Detail(update.BlogId);

            newBlog.CreateTime       = update.CreateTime;
            newBlog.Description      = update.Description;
            newBlog.EditTime         = DateTime.Now;
            newBlog.ShortDescription = update.ShortDescription;
            newBlog.Title            = update.Title;
            newBlog.UserEditBlog     = Microsoft.AspNet.Identity.IdentityExtensions.GetUserName(identity);
            newBlog.UserName         = update.UserName;

            if (src != null)
            {
                // получаем имя файла
                string fileName = System.IO.Path.GetFileName(src.FileName);
                //сохраняем файл в папку Files в проекте
                src.SaveAs(HttpContext.Current.Server.MapPath(@"~\Images\" + fileName));
                newBlog.ImagePath = @"~\Images\" + fileName;
            }
            context.Entry(newBlog).State = EntityState.Modified;
        }
        /// <summary>
        /// Checks if logged in user is an admin.
        /// </summary>
        /// <param name="user">A user that will be check for admin status.</param>
        /// <returns>A boolean value.</returns>
        public bool IsAdminUser(System.Security.Principal.IIdentity user)
        {
            //Do the stuff
            ApplicationDbContext db = new ApplicationDbContext();
            var UserManager         = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));

            //Get all of the roles associated with the user.
            var roles = UserManager.GetRoles(user.GetUserId());

            //Check if any of the roles are "Admin"
            if (roles.Count != 0)
            {
                foreach (var role in roles)
                {
                    if (role == "Admin")
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
示例#19
0
    // </snippet2>

    // <snippet3>
    // This example requires the System and System.Net namespaces.
    // <snippet8>
    public static string ClientInformation(HttpListenerContext context)
    {
        System.Security.Principal.IPrincipal user = context.User;
        System.Security.Principal.IIdentity  id   = user.Identity;
        if (id == null)
        {
            return("Client authentication is not enabled for this Web server.");
        }

        string display;

        if (id.IsAuthenticated)
        {
            display = String.Format("{0} was authenticated using {1}", id.Name,
                                    id.AuthenticationType);
        }
        else
        {
            display = String.Format("{0} was not authenticated", id.Name);
        }
        return(display);
    }
示例#20
0
        public static SetPermission GetPermissions(Domain.Models.Set set, System.Security.Principal.IIdentity user)
        {
            var perms = new SetPermission();

            perms.View = set.IsPublic;

            //only allow user owned sets to be changed in any capacity
            if (!String.IsNullOrEmpty(set.UserName))
            {
                //Authenticated users
                if (user != null && user.IsAuthenticated && !String.IsNullOrEmpty(user.Name))
                {
                    var isCurrentUserOwner = set.UserName.IsEqual(user.Name);

                    switch ((SetType)set.Type)
                    {
                    case SetType.Normal:
                        perms.View           = set.IsPublic || isCurrentUserOwner;
                        perms.Delete         = isCurrentUserOwner;
                        perms.EditList       = isCurrentUserOwner;
                        perms.EditProperties = isCurrentUserOwner;
                        break;

                    case SetType.Blocked:
                    case SetType.Front:
                    case SetType.Following:
                        perms.View           = isCurrentUserOwner;
                        perms.Delete         = false;
                        perms.EditList       = isCurrentUserOwner;
                        perms.EditProperties = false;
                        break;
                    }
                }
            }
            return(perms);
        }
示例#21
0
        public Authorization GetAuthorization(System.Security.Principal.IIdentity identity)
        {
            if (null == identity)
            {
                throw new ArgumentNullException("identity");
            }

            if (!(identity is ClaimsIdentity))
            {
                throw new NotSupportedException("Only identity from ClaimsIdentity are allowed.");
            }

            var claimsIdentity = (ClaimsIdentity)identity;

            // Create a UserProfile based on the identity received.
            var claimAuthorization = ExtractClaimValue(IdentityModel.Claims.ClaimTypes.Authorization, claimsIdentity.Claims);

            if (!String.IsNullOrWhiteSpace(claimAuthorization))
            {
                return(GetAuthorization(claimAuthorization));
            }

            return(new Authorization());
        }
示例#22
0
        /// <summary>
        /// Modified by Chandan added new parameter DataRow drSystemConfig
        /// task#2378 CopyrightInfo</summary>
        /// <param name="drUser"></param>
        /// <param name="drSystemConfig"></param>
        public StreamlinePrinciple(DataRow drUser, int ClientId)
        {
            try
            {
                ClientData = new DataSet();
                //string copyrightInfo = drSystemConfig["CopyrightInfo"].ToString(); //Added by Chandan task#2378 CopyrightInfo
                string copyrightInfo = "Copyright © 2001-" + DateTime.Now.Year.ToString() + " Streamline Healthcare Solutions, LLC. All Rights Reserved.";
                int    userId        = Convert.ToInt32(drUser["StaffId"]);
                identity    = new StreamlineIdentity(drUser);
                RefreshData = true;
                UserData objUserData = new UserData(drUser);

                getUserData(this, objUserData);
                //int ClientId = Convert.ToInt32(System.Web.HttpContext.Current.Request.QueryString["ClientId"].ToString());
                //Function Made by Sonia as ClientInformation has to be changed on changing the value of dropdown
                SetClientInformation(ClientId, true);
                //roleList = oUser.GetRoles(userId);
                // permissionList = oUser.GetPermission(userId);
            }
            catch (Exception ex)
            {
                if (ex.Data["CustomExceptionInformation"] == null)
                {
                    ex.Data["CustomExceptionInformation"] = "";
                }
                else
                {
                    ex.Data["CustomExceptionInformation"] = "";
                }
                if (ex.Data["DatasetInfo"] == null)
                {
                    ex.Data["DatasetInfo"] = null;
                }
                throw (ex);
            }
        }
示例#23
0
        protected override Task HandleRequirementAsync(
            AuthorizationHandlerContext authHandlerContext,
            UserIsAdminUserRequirement requirement)
        {
            System.Security.Principal.IIdentity userIdentity = authHandlerContext.User.Identity;

            if (userIdentity.Name != null)
            {
                // get user from app user database (if present)
                var appUser = _applicationContext.AppUser
                              .Where(a => a.NetworkId.ToLower() == userIdentity.Name.ToLower()).FirstOrDefault();

                // check if user is in app user database
                if (appUser != null)             // user IS in app user database
                {
                    if (appUser.UserRoleId == 3) // user is admin
                    {
                        authHandlerContext.Succeed(requirement);
                    }
                }
            }

            return(Task.CompletedTask);
        }
示例#24
0
        public override SiteMapNode BuildSiteMap()
        {
            lock (this)
            {
                //if (null == _rootNode)
                //{
                Clear();

                // Load the sitemap's xml from the file.
                XmlDocument siteMapXml = LoadSiteMapXml();

                // Create the first site map item from the top node in the xml.
                XmlElement rootElement = (XmlElement)siteMapXml.GetElementsByTagName(SiteMapNodeName)[0];

                System.Security.Principal.IIdentity userId = HttpContext.Current.User.Identity;
                if (!string.IsNullOrEmpty(userId.Name))
                {
                    AddUserAreaNodes(rootElement, userId.Name);
                }

                string projectID = (new Page().RouteData.Values["project_id"] as string);
                if (!string.IsNullOrEmpty(projectID) && projectID != "0")
                {
                    // This is the key method - add the dynamic nodes to the xml
                    AddProjectNodes(rootElement, projectID);
                    AddTreeLocationNodes(rootElement, projectID);
                }

                AddAboutNodes(rootElement);

                // Now build up the site map structure from the xml
                GenerateSiteMapNodes(rootElement);
                //}
            }
            return(_rootNode);
        }
示例#25
0
 public ClaimsIdentity(System.Security.Principal.IIdentity identity, System.Collections.Generic.IEnumerable <System.Security.Claims.Claim> claims, string authenticationType, string nameType, string roleType)
 {
 }
示例#26
0
 public ClaimsIdentity(System.Security.Principal.IIdentity identity, System.Collections.Generic.IEnumerable <System.Security.Claims.Claim> claims)
 {
 }
示例#27
0
    public static IEnumerable <Claim> Claims(this System.Security.Principal.IIdentity identity)
    {
        var claimsIdentity = (identity as ClaimsIdentity);

        return(claimsIdentity.Claims);
    }
示例#28
0
        public static string UsernameFromIdentity(string usernamePostfix, System.Security.Principal.IIdentity identity)
        {
            var identityName = identity.Name;

            return(identityName.Substring(0, identityName.IndexOf(usernamePostfix, StringComparison.Ordinal)));
        }
示例#29
0
 protected override void Initialize(System.Web.Routing.RequestContext requestContext)
 {
     base.Initialize(requestContext);
     _user = HttpContext.User.Identity;
 }
示例#30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                System.Security.Principal.IIdentity fred = HttpContext.Current.User.Identity;
                string s     = HttpContext.Current.User.Identity.Name;
                string s5    = Context.User.Identity.Name;
                string email = "";

                IOwinContext        ctx    = Request.GetOwinContext();
                ClaimsPrincipal     user   = ctx.Authentication.User;
                IEnumerable <Claim> claims = user.Claims;
                foreach (Claim c2 in claims)
                {
                    s = c2.Value;
                    if (c2.Type == "email")
                    {
                        email = s;
                    }
                    if (c2.Type == "person_id")
                    {
                        s5 = s;
                    }
                }
                //StreamWriter sw2 = new StreamWriter(@"c:/_TEMP_/StudentLogs_StartForm.txt", true);
                //sw2.WriteLine(email + "  :  " + s5+DateTime.Now.ToString()+" :  "+DateTime.Now.ToString());
                //sw2.Close();



                s = Request.QueryString["target"];
                if (s == "error")
                {
                    servercontent.InnerHtml = "<h3>error</h3>An unexpected error has occured. Please inform CC.";
                }
                string  path     = "";
                Guid    PersonID = new Guid();
                Utility u1       = new Utility();
                u1.GetPersonIdfromRequest(Request);

#if DEBUG
#endif
                Cerval_Configuration c = new Cerval_Configuration("StudentInformation_HomePageMessage");
                servercontent.InnerHtml = c.Value;
                bool show_photos = false;

                Utility u2 = new Utility();
                if (u1.Is_staff && (u2.Get_StaffCode(PersonID).Trim().ToUpper() == "CC"))
                {
                    show_photos = true;
                }
                //show_photos = true;

                if (PersonID != Guid.Empty)
                {
                    if ((u1.Is_student) && (u1.GetAdmissionNumber(PersonID) != 0))
                    {
                        string adno = u1.GetAdmissionNumber(PersonID).ToString();
                        path = Server.MapPath(@"App_Data/Results_names.txt");
                        try
                        {
                            using (StreamReader sr = new StreamReader(path))
                            {
                                while ((s = sr.ReadLine()) != null)
                                {
                                    if (s.Contains(adno))
                                    {
                                        show_photos = true;
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                    if (u1.Is_staff && (u2.Get_StaffCode(PersonID).Trim().ToUpper() == "CC"))
                    {
                        show_photos = true;
                    }
                }
            }
        }
示例#31
0
 /// <summary>
 /// �Ѿ���¼����֤
 /// </summary>
 /// <param name="userid"></param>
 public UserPrincipal(string userid)
 {
     identity = new UserIdentity(userid);
 }
示例#32
0
 public MyPrinciple(System.Security.Principal.IIdentity identity, string[] roles)
 {
     this.identity = identity;
     this.roles = roles;
 }
 public void SaveIdentity(System.Security.Principal.IIdentity identity, IToken token)
 {
     throw new Exception("The method or operation is not implemented.");
 }
 public WebPrinciple(int ID)
 {
     moduleSettings = ModuleConfig.GetSettings();
     Data.User user = new Data.User(moduleSettings);
     identity = new SiteIdentity(ID);
 }
示例#35
0
 public RolePrincipal(System.Security.Principal.IIdentity identity)
 {
 }
示例#36
0
 // Constructors
 public RolePrincipal(System.Security.Principal.IIdentity identity, string encryptedTicket)
 {
 }
示例#37
0
 public ClaimsPrincipal(System.Security.Principal.IIdentity identity)
 {
 }
示例#38
0
        public UserPrincipal(string userID, string password, int membertype)
        {
            identity = new UserIdentity(userID, password, membertype, out checkstatus, out userid);

            if (identity.IsAuthenticated)
            {

                //���ͨ����֤���ȡ���û���Role����������޸�Ϊ�����ݿ���

                //��ȡָ���û���Role��������ӵ�Role�У�������ֱ��Ϊ�û����һ��Admin��ɫ

                roleList = new ArrayList();

                roleList.Add("Admin");

            }
        }
示例#39
0
 public GenericPrincipal(System.Security.Principal.IIdentity identity, string[] roles)
 {
 }
示例#40
0
 protected bool IsAdmin()
 {
     System.Security.Principal.IIdentity userId = HttpContext.Current.User.Identity;
     return(((string[])(System.Web.HttpContext.Current.Cache[userId.Name]))[0] != null && ((string[])(System.Web.HttpContext.Current.Cache[userId.Name]))[0] == "admin");
 }
示例#41
0
 public SitePrincipal CreateInstance(string userName)
 {
     identity = siteIdentity.CreateInstance(userName) as SiteIdentity;
     CurrentRoles = new string[] { siteIdentity.Role };
     return this;
 }
示例#42
0
 public SitePrincipal CreateInstance(string userName)
 {
     identity = siteIdentity.CreateInstance(userName) as SiteIdentity;
     return this;
 }