Exemplo n.º 1
0
        public void CanReadXml()
        {
            var e = new BxlParser().Parse(@"
user login1 name1 hash=hash1 salt=salt1 publickey=key1
    domain = master1
    role role1
    role role2
    group grp1
    group grp2
    custom a=1 b=2
", "code", BxlParserOptions.ExtractSingle);
            var u = new User();

            UserSerializer.ReadXml(u, e);
            Assert.AreEqual("login1", u.Login);
            Assert.AreEqual("name1", u.Name);
            Assert.AreEqual("hash1", u.Hash);
            Assert.AreEqual("salt1", u.Salt);
            Assert.AreEqual("key1", u.PublicKey);
            Assert.AreEqual("master1", u.Domain);
            Assert.AreEqual("role1", u.Roles[0]);
            Assert.AreEqual("role2", u.Roles[1]);
            Assert.AreEqual("grp1", u.Groups[0]);
            Assert.AreEqual("grp2", u.Groups[1]);
            Assert.AreEqual("1", u.Custom["a"]);
            Assert.AreEqual("2", u.Custom["b"]);
        }
Exemplo n.º 2
0
        public UserSerializer GetUserByUserName(String userName)
        {
            UserModel      user   = this._userDao.GetByUserName(userName);
            UserSerializer result = new UserSerializer(user);

            return(result);
        }
Exemplo n.º 3
0
        public HttpResponseMessage CreateUser([FromBody] UserSerializer user)
        {
            try
            {
                //byte[] data = System.Text.Encoding.ASCII.GetBytes(user.Password);
                //data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
                //String hashedPassword = System.Text.Encoding.ASCII.GetString(data);

                string hashedPassword = BCrypt.Net.BCrypt.HashPassword(user.Password);

                Entities.UserCreate(user.FirstName, user.LastName, user.Username, user.Email, hashedPassword);


                return(Request.CreateResponse(HttpStatusCode.OK, new ResponseMessage
                {
                    Success = true,
                    Data = user,
                    Message = "User has been created!"
                }));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, new ResponseMessage
                {
                    Success = false,
                    Message = ex.Message
                }));
            }
        }
Exemplo n.º 4
0
        public IUser Store(IUser user)
        {
            if (!WriteUsersEnabled)
            {
                throw new Exception("not enabled");
            }
            lock (this) {
                user.Id = UserSerializer.GetId(user);
                if (user.CreateTime.Year <= 1900)
                {
                    user.CreateTime = DateTime.Now.ToUniversalTime();
                }
                user.UpdateTime = DateTime.Now.ToUniversalTime();
                var json = UserSerializer.GetJson(user, "store");
                var url  = GetBaseUrl() + user.Id + "?refresh=true";

                var result = EsClient.ExecuteCommand(url, json);
                if (null == result)
                {
                    throw new Exception("invalid storage operation", EsClient.LastError);
                }
                var j       = result.jsonify();
                var version = j.num("_version");
                user.Version       = version;
                _cache[user.Login] = user;
                return(user);
            }
        }
Exemplo n.º 5
0
        public UserSerializer GetUserById(int id)
        {
            UserModel      user   = this._userDao.GetById(id);
            UserSerializer result = new UserSerializer(user);

            return(result);
        }
Exemplo n.º 6
0
 public ResponseSerializer Put(int id, [FromBody] UserSerializer userSerializer)
 {
     return(new ResponseSerializer(
                200,
                "success",
                this._userBus.UpdateUser(id, userSerializer)
                ));
 }
Exemplo n.º 7
0
 public ResponseSerializer Post([FromBody] UserSerializer userSerializer)
 {
     return(new ResponseSerializer(
                200,
                "success",
                this._userBus.CreateNewUser(userSerializer)
                ));
 }
Exemplo n.º 8
0
        public void CanWriteJson()
        {
            var user = GetUser(0);
            var js   = UserSerializer.GetJson(user, "store").Simplify(SimplifyOptions.SingleQuotes);

            Console.WriteLine(js);
            Assert.AreEqual(@"{'__id':null,'__version':0,'createtime':'0001-01-01T00:00:00+0000','updatetime':'0001-01-01T00:00:00+0000','class':'user','__type':'user','netclass':'qorpent.v2.security.user.User, qorpent.v2.security','login':'******','name':'myname0','email':'email0','admin':true,'isgroup':false,'active':false,'expire':'2015-12-31T19:00:00+0000','publickey':'LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tDQpNSUlDV0RDQ0FjR2dBd0lCQWdJSkFKWjdOK1pyeWJ1K01BMEdDU3FHU0liM0RRRUJCUVVBTUVVeEN6QUpCZ05WDQpCQVlUQWtGVk1STXdFUVlEVlFRSURBcFRiMjFsTFZOMFlYUmxNU0V3SHdZRFZRUUtEQmhKYm5SbGNtNWxkQ0JYDQphV1JuYVhSeklGQjBlU0JNZEdRd0hoY05NVFV3TlRJMk1UUTFPRE15V2hjTk1UWXdOVEkxTVRRMU9ETXlXakJGDQpNUXN3Q1FZRFZRUUdFd0pCVlRFVE1CRUdBMVVFQ0F3S1UyOXRaUzFUZEdGMFpURWhNQjhHQTFVRUNnd1lTVzUwDQpaWEp1WlhRZ1YybGtaMmwwY3lCUWRIa2dUSFJrTUlHZk1BMEdDU3FHU0liM0RRRUJBUVVBQTRHTkFEQ0JpUUtCDQpnUURiNUQ1QncySjMyRURUK1BiVHB6SC9PYVYwcUlqc2VQV3hlWnVTS2tMbHhnVFQ3RWZZTHNnK3phYldmamw0DQo4VHU4MWd5QklQeXVHZE81cFpMZGF6MVFOaTBTMXJiL2N0TjRvZkI4Rm9hSW13L0hRdEdTbmdtbjEwRjh5c0ZsDQo4bzMvTXRNMFp1cGM2RjRlSWtTbmRuUDRxWVk4U1JnZC9YbTNQc25iKzBsS0dRSURBUUFCbzFBd1RqQWRCZ05WDQpIUTRFRmdRVWI2cnFXWXBhWnkraE11amYxNE9FS00ycXZIa3dId1lEVlIwakJCZ3dGb0FVYjZycVdZcGFaeStoDQpNdWpmMTRPRUtNMnF2SGt3REFZRFZSMFRCQVV3QXdFQi96QU5CZ2txaGtpRzl3MEJBUVVGQUFPQmdRQmlUeGkyDQpmbERBcU41YTV1VEE1cUdRRzVJWkM1U1dGL0t6S2dRSGYwODBtMzUxZUNVTHJ3djZMb1E3MTg0MnJSYW12aVdrDQp6QVVQb0NWWVNZQUwvb3JONVNrQWJiVGV6VVlFQTRTMDdxWXd1Vkt4L3llUTBOWG1CT2lIak1pU210MkVUcldPDQpkaXkxK0F4NG1WdkdhMFpQS01oRWYweFRkc1BFeUpjRVpTN1d4dz09DQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tDQo=','hash':'16e001a08cece49745cf04470aabd1d1','salt':'salt1','resetkey':null,'resetexpire':'0001-01-01T00:00:00+0000','logable':false,'domain':'master0','roles':['role1_0','role2_0'],'groups':['grp1_0','grp2_0'],'custom':{'a':'1_0','b':'2_0'}}", js);
        }
Exemplo n.º 9
0
 public void PerformanceTest()
 {
     CheckRate(i => {
         var usr  = GetUser(i % 100);
         var json = UserSerializer.GetJson(usr, "store");
         var usr1 = UserSerializer.CreateFromJson(json);
     });
 }
Exemplo n.º 10
0
        public void LoadUserConfiguration()
        {
            config = UserSerializer.Deserialize();
            if (config == null)
            {
                config = new UserConfiguration();
                access.DisplayWelcomeDialog();
            }

            access.SetUserConfig(config);
        }
Exemplo n.º 11
0
        public String CreateNewUser(UserSerializer userSerializer)
        {
            UserModel userModel = new UserModel();

            userModel.UserName    = userSerializer.userName;
            userModel.DisplayName = userSerializer.displayName;
            userModel.Password    = userSerializer.password;
            userModel.Email       = userSerializer.email;
            userModel.PhoneNumber = userSerializer.phoneNumber;
            userModel.Remark      = userSerializer.remark;
            return(this._userDao.Create(userModel));
        }
Exemplo n.º 12
0
        public String UpdateUser(int id, UserSerializer userSerializer)
        {
            UserModel userModel = new UserModel();

            userModel.Id          = id;
            userModel.UserName    = userSerializer.userName;
            userModel.DisplayName = userSerializer.displayName;
            userModel.Password    = userSerializer.password;
            userModel.Email       = userSerializer.email;
            userModel.PhoneNumber = userSerializer.phoneNumber;
            userModel.Remark      = userSerializer.remark;
            return(this._userDao.Update(id, userModel));
        }
Exemplo n.º 13
0
 public IUser GetUser(string login)
 {
     if (!WriteUsersEnabled)
     {
         return(null);
     }
     lock (this) {
         CheckCache();
         if (EsClient.InvalidConnection)
         {
             return(null);
         }
         if (_cache.ContainsKey(login))
         {
             return(_cache[login]);
         }
         string json;
         if (login.StartsWith("!certid:"))
         {
             var post = new { query = new { match = new { publickey = login.Replace("!certid:", "") } } }.stringify();
             json = EsClient.ExecuteCommand(GetBaseUrl() + "_search", post);
         }
         else
         {
             var id = UserSerializer.GetId(login);
             json = EsClient.ExecuteCommand(GetBaseUrl() + id);
         }
         if (null == json)
         {
             return(null);
         }
         var j     = json.jsonify();
         var found = j.bul("found") || j.num("*.total") > 0;
         if (found)
         {
             var src     = j.map("*._source");
             var version = j.resolvenum("_version", "__version");
             var user    = UserSerializer.CreateFromJson(src);
             user.Id       = j.resolvestr("_id", "__id");
             user.Version  = version;
             _cache[login] = user;
         }
         else
         {
             _cache[login] = null;
         }
         return(_cache[login]);
     }
 }
Exemplo n.º 14
0
        public IEnumerable <IUser> SearchUsers(UserSearchQuery query)
        {
            var q = string.IsNullOrWhiteSpace(query.Query)? "login:*" : query.Query;

            if (!string.IsNullOrWhiteSpace(query.Login))
            {
                q += " AND login:"******" AND name:" + query.Name;
            }
            if (!query.Groups)
            {
                q += " AND NOT isgroup:true";
            }
            if (!query.Users)
            {
                q += " AND isgroup:true";
            }
            if (!string.IsNullOrWhiteSpace(query.Domain))
            {
                q += " AND domain:" + query.Domain;
            }
            var esquery = new {
                query = new { query_string = new { query = q } }
            };
            var json = EsClient.ExecuteCommand(GetBaseUrl() + "_search", esquery.stringify());

            if (null == json)
            {
                yield break;
            }
            var j    = json.jsonify();
            var hits = j.arr("hits.hits");

            foreach (var hit in hits)
            {
                var src     = hit.map("*._source");
                var version = hit.resolvenum("_version", "__version");
                var user    = UserSerializer.CreateFromJson(src);
                user.Id            = hit.resolvestr("_id", "__id");
                user.Version       = version;
                _cache[user.Login] = user;
                yield return(user);
            }
        }
Exemplo n.º 15
0
        public void Test()
        {
            using var stream = new MemoryStream();
            var serializer = new UserSerializer();

            int total = 0, idx;

            Span <byte> span = stackalloc byte[32];

            for (idx = 0; idx < 10000; idx++)
            {
                var length = serializer.Serialize(new User {
                    Login = idx.ToString(), Pass = idx.ToString(), Bio = idx.ToString(), Created = DateTime.MaxValue
                }, span);
                stream.Write(span.Slice(0, length));
                total += length;
            }

            var lastLength = serializer.Serialize(new User {
                Login = "******", Pass = "******", Bio = "bad", Created = DateTime.MaxValue
            }, span);

            stream.Write(span.Slice(lastLength - 1));

            stream.Flush();
            stream.Seek(0, SeekOrigin.Begin);

            Span <byte> buffer = stackalloc byte[32];
            var         reader = new ItemReader <User>(stream, buffer, serializer);

            for (idx = 0; idx < 10000; idx++)
            {
                Assert.IsTrue(reader.TryReadItem(out var user));
                Assert.IsTrue(user != null);

                var val = idx.ToString();
                Assert.AreEqual(val, user.Login);
                Assert.AreEqual(val, user.Pass);
                Assert.AreEqual(val, user.Bio);
                Assert.AreEqual(DateTime.MaxValue, user.Created);
            }

            Assert.IsFalse(reader.TryReadItem(out _));
            Assert.AreEqual(total, reader.TotalBytesRead);
        }
Exemplo n.º 16
0
        public void Setup()
        {
            var ping = ExecuteCommand("http://127.0.0.1:9200/_cluster/health");

            if (null == ping)
            {
                _ignore = true;
            }
            else
            {
                var user   = GetUser(0);
                var userJs = UserSerializer.GetJson(user);
                var id     = UserSerializer.GetId(user);
                ExecuteCommand("http://127.0.0.1:9200/elasticusersourcetest", method: "DELETE");
                var result = ExecuteCommand("http://127.0.0.1:9200/elasticusersourcetest/pwd/" + id, userJs);
                Assert.NotNull(result);
            }
            _es       = new ElasticUserSource();
            _es.Index = "elasticusersourcetest";
        }
Exemplo n.º 17
0
        public HttpResponseMessage UpdateUser([FromBody] UserSerializer user)
        {
            try
            {
                var res = Entities.UserUpdate(CurrentIdentity.UserId, user.FirstName, user.MiddleName, user.LastName, user.Bio);

                return(Request.CreateResponse(HttpStatusCode.OK, new ResponseMessage
                {
                    Success = true,
                    Message = "User information updated.",
                    Data = res
                }));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, new ResponseMessage
                {
                    Success = false,
                    Message = ex.Message
                }));
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Overridden to append values to the <c>InitParameters</c>.
        /// </summary>
        /// <remarks>
        /// Injecting here allows us to append our values for serialization to the
        /// client without modifying <c>InitParameters</c>. This method will be invoked
        /// immediately before writing the parameters to HTML in the base class.
        /// </remarks>
        /// <returns>See <see cref="Silverlight.GetSilverlightParameters"/></returns>
        protected override IDictionary <string, string> GetSilverlightParameters()
        {
            IDictionary <string, string> dictionary = base.GetSilverlightParameters();

            // Create a builder for InitParams
            StringBuilder initParamsBuilder = new StringBuilder();

            if (dictionary.ContainsKey("InitParams"))
            {
                initParamsBuilder.Append(dictionary["InitParams"]);
            }

            // Serialize the user
            if (this.EnableUserState && (UserService.Current != null))
            {
                string serializedUser = HttpUtility.UrlEncode(
                    UserSerializer.SerializeUser(
                        UserService.Current.InternalDomainService,
                        UserService.Current.User));

                if (!string.IsNullOrEmpty(serializedUser))
                {
                    SilverlightApplication.AppendInitParameter(
                        initParamsBuilder,
                        UserSerializer.UserKey,
                        serializedUser);
                }
            }

            // Commit updated InitParams to dictionary
            if (initParamsBuilder.Length > 0)
            {
                dictionary["InitParams"] = initParamsBuilder.ToString();
            }

            return(dictionary);
        }
Exemplo n.º 19
0
 public override void Initialize()
 {
     lock (this) {
         Setup();
         if (File.Exists(ResolvedFilePath))
         {
             _file = ResolvedFilePath;
             var bsharpresult = BSharpCompiler.CompileFile(_file);
             foreach (
                 var cls in
                 bsharpresult.ResolveAll("pwd").OrderBy(_ => _.Compiled.Attr("idx").ToInt()))
             {
                 foreach (var element in cls.Compiled.Elements("usr"))
                 {
                     var record = new User();
                     UserSerializer.ReadXml(record, element);
                     _cache[record.Login] = record;
                 }
             }
             LastCheck    = DateTime.Now;
             LastFileTime = File.GetLastWriteTime(_file);
         }
     }
 }
Exemplo n.º 20
0
        public async Task <IActionResult> Register([FromForm] UserSerializer model)
        {
            if (ModelState.IsValid)
            {
                User user = new User {
                    Email = model.Email, Age = model.Age, UserName = model.UserName
                };
                if (!_roleManager.RoleExistsAsync(model.RoleName).Result)
                {
                    return(BadRequest("Error role!"));
                }
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    if (_roleManager.RoleExistsAsync(model.RoleName).Result)
                    {
                        await _userManager.AddToRoleAsync(user, model.RoleName);
                    }

                    return(Ok(new { user = user, role = _userManager.GetRolesAsync(user) }));
                }
                return(BadRequest(result.Errors));
            }
            // Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>();
            // foreach(var key in ModelState.Keys){
            //     if(ModelState[key].Errors.Count != 0)
            //     {
            //         errors[key] = new List<string>();
            //         foreach(var error in ModelState[key].Errors){
            //             errors[key].Add(error.ErrorMessage);
            //         }
            //     }
            // }
            return(BadRequest());
        }
Exemplo n.º 21
0
        public HttpResponseMessage Authenticate(UserSerializer userSerializer)
        {
            try
            {
                var response = new List <object>();

                var foundUser =
                    Entities.Users.SingleOrDefault(u => u.Email == userSerializer.Username ||
                                                   u.Username == userSerializer.Username);
                if (foundUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.NotFound, new ResponseMessage
                    {
                        Success = false,
                        Message = "Username not found."
                    }));
                }

                if (!BCrypt.Net.BCrypt.Verify(userSerializer.Password, foundUser.Password))
                {
                    return(Request.CreateResponse(HttpStatusCode.NotFound, new ResponseMessage
                    {
                        Success = false,
                        Message = "The password does not match."
                    }));
                }
                var tags = Entities.UserTagsGet(foundUser.Id).ToList();

                var t = new List <Models.Tag>();
                foreach (var tag in tags)
                {
                    t.Add(new Models.Tag
                    {
                        TagId     = tag.TagId,
                        Name      = tag.Name,
                        CreatedAt = tag.CreatedAt,
                        CreatedBy = tag.CreatedBy
                    });
                }

                Models.User user = new Models.User
                {
                    TotalFollowers = Entities.Follows.Count(f => f.FollowedId == foundUser.Id),
                    TotalPosts     = Entities.Posts.Count(p => p.UserId == foundUser.Id && p.TypeId != 3),
                    TotalBlogs     = Entities.Posts.Count(p => p.UserId == foundUser.Id && p.TypeId == 3),
                    UserTags       = new List <Tag>(t)
                };

                foundUser.CopyProperties <Data.User, Models.User>(user);



                var jwt = JWTokenHelper.GenerateJWToken(user);

                response.Add(user);
                response.Add(jwt);

                return(Request.CreateResponse(HttpStatusCode.OK, new ResponseMessage
                {
                    Success = true,
                    Message = "User authenticated.",
                    Data = response
                }));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, new ResponseMessage
                {
                    Success = false,
                    Message = ex.Message
                }));
            }
        }
Exemplo n.º 22
0
 public void SaveUserConfiguration()
 {
     UserSerializer.Serialize(config);
     access.SetUserConfig(config);
 }