예제 #1
0
파일: EmbyApi.cs 프로젝트: anonaut/Ombi
        public EmbyUser LogIn(string username, string password, string apiKey, Uri baseUri)
        {
            var request = new RestRequest
            {
                Resource = "emby/users/authenticatebyname",
                Method   = Method.POST
            };

            var body = new
            {
                username,
                password    = StringHasher.GetSha1Hash(password).ToLower(),
                passwordMd5 = StringHasher.CalcuateMd5Hash(password)
            };

            request.AddJsonBody(body);

            request.AddHeader("X-Emby-Authorization",
                              $"MediaBrowser Client=\"Ombi\", Device=\"Ombi\", DeviceId=\"{AssemblyHelper.GetProductVersion()}\", Version=\"{AssemblyHelper.GetAssemblyVersion()}\"");
            AddHeaders(request, apiKey);


            var policy = RetryHandler.RetryAndWaitPolicy((exception, timespan) => Log.Error(exception, "Exception when calling LogInfor Emby, Retrying {0}", timespan), new[] {
                TimeSpan.FromSeconds(1)
            });

            var obj = policy.Execute(() => Api.Execute(request, baseUri));

            if (obj.StatusCode == HttpStatusCode.Unauthorized)
            {
                return(null);
            }

            return(JsonConvert.DeserializeObject <EmbyUserLogin>(obj.Content)?.User);
        }
예제 #2
0
        static void Prepare()
        {
            StringHasher.Initialize(m_directory);
            FileLogger.Initialize(m_directory);

            Utility.TestUtility();
        }
 public TestServiceTest()
 {
     this._testRepositoryMock       = new Mock <ITestRepository>();
     this._testAnswerRepositoryMock = new Mock <IUserTestAnswersRepository>();
     this._mapper = new MapperConfiguration(cfg => cfg.AddMaps(typeof(TestProfile))).CreateMapper();
     this._hasher = new StringHasher(new HashParameters(100, new byte[] { 1, 2 }));
 }
예제 #4
0
        static void Bastard_Prepare()
        {
            // TODO TODO TODO
            if (Config.DumpInfo)
            {
                Utils.Bastard.Fail("**** Not implemented yet! ****");
            }

            if (Config.DebugLog)
            {
                var debugLog = Path.Combine(MyDirectory, "debug.log");

                if (File.Exists(debugLog))
                {
                    File.Delete(debugLog);
                }

                Snoopy = new TextWriterTraceListener(debugLog, "DEBUG_LOG");

                Debug.AutoFlush = true;

                Debug.Listeners.Clear();
                Debug.Listeners.Add(Snoopy);
            }

            if (Config.Silent)
            {
                Console.SetOut(TextWriter.Null);
                Console.SetError(TextWriter.Null);
            }

            StringHasher.Initialize(MyDirectory);
            AttributeTypes.Initialize(MyDirectory);
            ResourceFactory.Initialize(MyDirectory);
        }
예제 #5
0
 private Response GetGravatarImage()
 {
     if (LoggedIn)
     {
         var user   = UserHelper.GetUser(Username);
         var hashed = StringHasher.CalcuateMd5Hash(user.EmailAddress);
         if (string.IsNullOrEmpty(hashed))
         {
             return(Response.AsJson(new JsonResponseModel
             {
                 Result = false
             }));
         }
         return
             (Response.AsJson(new JsonResponseModel
         {
             Result = true,
             Message = $"https://www.gravatar.com/avatar/{hashed}"
         }));
     }
     else
     {
         return(Response.AsJson(new JsonResponseModel {
             Result = false
         }));
     }
 }
예제 #6
0
        static void SnoopFile(string filename)
        {
            XDocument xml = null;

            if (!Utils.TryLoadXmlFile(filename, out xml))
            {
                Utils.Bastard.Fail("Snoopy only works with XML files.");
            }

            var strs = new HashSet <String>();

            foreach (var name in EnumerateXMLNames(xml.Root))
            {
                var id = new StringId(name.LocalName);

                if (!strs.Contains(id) && !StringHasher.CanResolveHash(id))
                {
                    strs.Add(id);
                }
            }

            if (strs.Count == 0)
            {
                Utils.Bastard.Fail("Couldn't find anything new, sadly.");
            }

            var outFile = Path.ChangeExtension(filename, ".snoop.log");

            File.WriteAllText(outFile, String.Join("\n", strs.OrderBy((s) => s)));
        }
 public LoginCommandHandler(
     IAuthenticationRepository authRepository,
     StringHasher hasher)
 {
     _hasher         = hasher;
     _authRepository = authRepository;
 }
예제 #8
0
        private static void WriteNode(XmlWriter writer,
                                      IEnumerable <BinaryObject> parentChain,
                                      BinaryObject node)
        {
            var chain = parentChain.Concat(new[] { node });

            writer.WriteStartElement("object");

            // get object name from object hash via string list
            var objectHashInput = (int)node.NameHash;

            if (StringHasher.CanResolveHash(objectHashInput))
            {
                var objectHashOutput = StringHasher.ResolveHash(objectHashInput);

                writer.WriteAttributeString("name", objectHashOutput);
            }
            else
            {
                writer.WriteAttributeString("hash", node.NameHash.ToString("X8"));
            }

            WriteNodeField(writer, node);

            foreach (var childNode in node.Children)
            {
                WriteNode(writer, chain, childNode);
            }

            writer.WriteEndElement();
        }
예제 #9
0
        public bool DoesPasswordMatchHash(string email, string nonHashedPassword)
        {
            var user = context.Users.First(e => e.Email.Equals(email.ToLower()));

            var hashedPassword = StringHasher.Hash(nonHashedPassword);

            return(user.Password.Equals(hashedPassword));
        }
예제 #10
0
        public AuthenticationResultModel Authenticate(AuthenticationRequestModel request)
        {
            var account = AuthRepo.GetAuthenticationAccount(request.UserId);

            var result = new AuthenticationResultModel();

            if (account == null)
            {
                result.Result = AuthenticationResultType.Invalid;
                return(result);
            }

            if (StringHasher.ValidateHashedString(account.HashedPassword, request.Password))
            {
                if (account.Locked)
                {
                    result.Result = AuthenticationResultType.Locked;
                    return(result);
                }

                result.Result = account.ChangePassword
                    ? AuthenticationResultType.ChangePassword
                    : AuthenticationResultType.Success;
            }
            else if (!account.Locked && account.HashedPassword.Equals(request.Password))
            {
                // 일반 문자열 비밀번호 확인
                result.Result = AuthenticationResultType.ChangePassword;
            }
            else
            {
                // 비밀번호가 맞지 않음
                result.Result = AuthenticationResultType.Invalid;
                return(result);
            }

            var tokenModel = new AuthenticationTokenModel
            {
                UserId    = account.UserId,
                Name      = account.Name,
                Company   = account.CompanyCode ?? "",
                Group     = account.GroupCode ?? "",
                UserClass = account.UserClass ?? "",
                UniqueId  = Guid.NewGuid().ToString("N")
            };

            var tokenClaims = tokenModel.ToClaims();

            var token =
                TokenProvider.GetJwtSecurityToken(tokenClaims,
                                                  result.Result == AuthenticationResultType.ChangePassword
                        ? TemporaryTokenExpireMins
                        : (int?)null);

            result.Token = new JwtSecurityTokenHandler().WriteToken(token);

            return(result);
        }
예제 #11
0
        private TokenType SkipNumber(char ch, StringBuilder buffer, ref int hash)
        {
            StringHasher hasher = StringHasher.Create();

            if (ch == '-')
            {
                hasher.AddChar(ch);
                buffer?.Append(ch);
                ch = this.NextChar();
            }

            if (!Tokenizer.IsDigit(ch))
            {
                return(TokenType.Error);
            }

            ch = this.SkipDigits(ch, buffer, ref hasher);

            if (ch == '.')
            {
                hasher.AddChar(ch);
                buffer?.Append(ch);
                ch = this.NextChar();

                if (!Tokenizer.IsDigit(ch))
                {
                    return(TokenType.Error);
                }

                ch = this.SkipDigits(ch, buffer, ref hasher);
            }

            if (ch == 'e' || ch == 'E')
            {
                hasher.AddChar(ch);
                buffer?.Append(ch);
                ch = this.NextChar();

                if (ch == '-' || ch == '+')
                {
                    hasher.AddChar(ch);
                    buffer?.Append(ch);
                    ch = this.NextChar();
                }

                if (!Tokenizer.IsDigit(ch))
                {
                    return(TokenType.Error);
                }

                this.SkipDigits(ch, buffer, ref hasher);
            }

            hash = hasher.HashValue;
            Debug.Assert(buffer == null || StringHasher.HashSubstring(buffer.ToString(), 0, buffer.Length) == hash);

            return(TokenType.Number);
        }
예제 #12
0
        public void WriteStringWithHash(uint version, string value)
        {
            WriteString(value);

            if (version > 0x1080000)
            {
                WriteInt32(StringHasher.GenerateStringHash(value));
            }
        }
        private static AdminService PrepareSUT(ApplicationDbContext context)
        {
            var mapper               = new MapperConfiguration(cfg => cfg.AddMaps(typeof(TestProfile))).CreateMapper();
            var testRepository       = new TestRepository(context);
            var testAnswerRepository = new UserTestAnswersRepository(context);
            var stringHasher         = new StringHasher(new HashParameters(100, new byte[] { 1, 2 }));

            return(new AdminService(testRepository, testAnswerRepository, mapper, stringHasher));
        }
예제 #14
0
        public User Create(string username, string twitchId, string youTubeId, string password = null)
        {
            User user = gameData.CreateUser();

            user.TwitchId     = twitchId;
            user.YouTubeId    = youTubeId;
            user.Username     = username;
            user.PasswordHash = StringHasher.Get(password);
            return(user);
        }
예제 #15
0
        public static void ChangeUserHash(int userId, out string hash, out string guid)
        {
            User user = User.Get(userId);

            user.Guid = GeneralUtils.GetGuid();
            User.Update(user);

            hash = StringHasher.HashString(user.Email);
            guid = user.Guid;
        }
예제 #16
0
        private char SkipDigits(char ch, StringBuilder buffer, ref StringHasher hasher)
        {
            do
            {
                hasher.AddChar(ch);
                buffer?.Append(ch);
                ch = this.NextChar();
            }while (Tokenizer.IsDigit(ch));

            return(ch);
        }
예제 #17
0
        public void TestHashingString()
        {
            var sh = new StringHasher(Hasher.HashAlgos.MD5, "123456");

            Assert.Equal("E10ADC3949BA59ABBE56E057F20F883E", sh.HashResult);
            sh = new StringHasher(Hasher.HashAlgos.SHA1, "123456");
            Assert.Equal("7C4A8D09CA3762AF61E59520943DC26494F8941B", sh.HashResult);
            sh = new StringHasher(Hasher.HashAlgos.SHA256, "123456");
            Assert.Equal("8D969EEF6ECAD3C29A3A629280E686CF0C3F5D5A86AFF3CA12020C923ADC6C92", sh.HashResult);
            sh = new StringHasher(Hasher.HashAlgos.SHA512, "123456");
            Assert.Equal("BA3253876AED6BC22D4A6FF53D8406C6AD864195ED144AB5C87621B6C233B548BAEAE6956DF346EC8C17F5EA10F35EE3CBC514797ED7DDD3145464E2A0BAB413", sh.HashResult);
        }
예제 #18
0
        /// <summary>
        /// Checks if the user with the specified ID has used the specified password
        /// recently (ie. within the last 24 password changes).
        /// Returns true if they have, otherwise false.
        /// </summary>
        public static bool IsRecentPassword(User user, string password)
        {
            // Get the last 24 passwords
            UserPasswordHistoryFinder finder = new UserPasswordHistoryFinder {
                UserId = user.UserId.GetValueOrDefault(-1), MaxRecords = 24
            };

            finder.SortExpressions.Add(new DescendingSort(UserPasswordHistory.Columns.Date));
            EntityList <UserPasswordHistory> passwordHistory = UserPasswordHistory.FindMany(finder);

            return(passwordHistory.Any(uph => StringHasher.VerifyHash(uph.Password, password + user.PasswordSalt)));
        }
예제 #19
0
        public void WriteStringWithHash(uint version, string value, bool withPadding = false, bool isCatherineFullBodyData = false)
        {
            WriteString(value);

            if (isCatherineFullBodyData && withPadding)
            {
                WriteByte(0);   // padding byte
            }
            if (version > 0x1080000)
            {
                WriteInt32(StringHasher.GenerateStringHash(value));
            }
        }
        public HasherResolver(EqualityContext context, MembersProvider membersProvider, IConfigurationProvider configuration)
        {
            _configuration = configuration;

            _hashersFactories = new Func <IVariable, IHasherEmitter>[] {
                variable => NullableHasher.Create(this, variable),
                variable => StringHasher.Create(_configuration, variable),
                BasicHasher.Create,
                variable => MembersHasher.Create(this, membersProvider, _configuration, variable),
                variable => ArrayHasher.Create(this, _configuration, variable),
                variable => EnumerablesHasher.Create(this, _configuration, variable),
                variable => IndirectHasher.Create(context, variable)
            };
        }
예제 #21
0
        public static User GetUser(int userId, string hash, string guid)
        {
            UserFinder finder = new UserFinder {
                UserId = userId, Guid = guid
            };
            User u = User.FindOne(finder);

            if (StringHasher.VerifyHash(hash, u.Email))
            {
                return(u);
            }

            return(User.Empty);
        }
예제 #22
0
        private void WriteStringWithHash(uint version, string value)
        {
            WriteString(value);

            if (version > 0x1080000)
            {
                WriteInt(StringHasher.GenerateStringHash(value));

                // if ( version <= 0x1104990 )
                // {
                //    hash = StringHasher.GenerateStringHash(str); // TODO: unsupported hash algo?
                // }
            }
        }
예제 #23
0
        private static void WriteRootNode(XmlWriter writer,
                                          IEnumerable <BinaryObject> parentChain,
                                          BinaryObjectFile bof)
        {
            BinaryObject node = bof.Root;

            var chain = parentChain.Concat(new[] { node });

            writer.WriteStartElement("object");

            // get object name from object hash via string list
            var objectHashInput = (int)node.NameHash;

            if (StringHasher.CanResolveHash(objectHashInput))
            {
                var objectHashOutput = StringHasher.ResolveHash(objectHashInput);

                writer.WriteAttributeString("name", objectHashOutput);
            }
            else
            {
                writer.WriteAttributeString("hash", node.NameHash.ToString("X8"));
            }

            // add version attribute to root object
            string bofVersion = bof.Version.ToString();

            if (bofVersion != null)
            {
                writer.WriteAttributeString("version", bofVersion);
            }

            // add header attribute to root object
            string bofHeader = bof.Header;

            if (bofHeader.Length > 0)
            {
                writer.WriteAttributeString("header", bofHeader);
            }

            WriteNodeField(writer, node);

            foreach (var childNode in node.Children)
            {
                WriteNode(writer, chain, childNode);
            }

            writer.WriteEndElement();
        }
예제 #24
0
        public CouchPotatoApiKey GetApiKey(Uri baseUrl, string username, string password)
        {
            var request = new RestRequest
            {
                Resource = "getkey/?u={username}&p={password}",
                Method   = Method.GET
            };

            request.AddUrlSegment("username", StringHasher.CalcuateMd5Hash(username));
            request.AddUrlSegment("password", StringHasher.CalcuateMd5Hash(password));

            var obj = RetryHandler.Execute(() => Api.Execute <CouchPotatoApiKey>(request, baseUrl),
                                           (exception, timespan) => Log.Error(exception, "Exception when calling GetApiKey for CP, Retrying {0}", timespan), null);

            return(obj);
        }
예제 #25
0
 static void Bastard_Think()
 {
     if (Config.SuperHasher9000)
     {
         RunSuperHasher9000TM();
     }
     else if (Config.HasArg("dumpstr"))
     {
         Utils.Bastard.Say("Dumping strings data...");
         StringHasher.Dump(MyDirectory);
     }
     else
     {
         Bastard_WorkNEW();
     }
 }
예제 #26
0
        public void CreateAccount(User user)
        {
            if (HasAccount(user.Email))
            {
                throw new ArgumentException($"The user account with email address {user.Email} exists.");
            }

            if (!IsValidPassword(user.Password))
            {
                throw new Exception("The password provided is not valid. Must be a minimum length of 8 and at least one number!");
            }

            user.Email    = user.Email.ToLower();
            user.Password = StringHasher.Hash(user.Password);

            context.Users.Attach(user);
            context.Users.Add(user);
            context.SaveChanges();
        }
예제 #27
0
        public static void Seed(CinemaContext context)
        {
            var hasher = new StringHasher();

            for (int i = 1; i <= 10; i++)
            {
                context.Users.Add(new User
                {
                    Id    = Guid.NewGuid(),
                    Name  = "User" + i,
                    Email = i + "@movie.com",
                    ContactByEmailAllowed = true,
                    MobilePhone           = "" + i + i + i + i + i,
                    ContactBySmslAllowed  = true,
                    Password     = hasher.GetHash("123", "user" + i),
                    PasswordSalt = "user" + i,
                    Role         = "User",
                    UserType     = (UserType)(i % 3)
                });
            }

            for (int i = 1; i <= 5; i++)
            {
                context.Users.Add(new User
                {
                    Id    = Guid.NewGuid(),
                    Name  = "Editor" + i,
                    Email = "editor" + i + "@movie.com",
                    ContactByEmailAllowed = true,
                    MobilePhone           = "" + i + i + i + i + i,
                    ContactBySmslAllowed  = true,
                    Password     = hasher.GetHash("123", "editor" + i),
                    PasswordSalt = "editor" + i,
                    Role         = "Editor",
                    UserType     = (UserType)(i % 3)
                });
            }

            context.SaveChanges();
        }
예제 #28
0
        private static FieldInfo ResolveField(uint key, byte[] value)
        {
            FieldInfo field = new FieldInfo();

            // key
            string keyTypeString = "hash";
            string keyNameString = $"{key:X8}";

            if (StringHasher.CanResolveHash((int)key))
            {
                keyTypeString = "name";
                keyNameString = StringHasher.ResolveHash((int)key);
            }

            // value
            string valueTypeString  = FieldHandling.GetTypeName(FieldType.BinHex);
            string valueValueString = BitConverter.ToString(value).Replace("-", "");

            string r_valueTypeString  = valueTypeString;
            string r_valueValueString = valueValueString;

            if (TypeGuesser.FieldHandler(value, out r_valueTypeString, out r_valueValueString) == true)
            {
                valueTypeString  = r_valueTypeString;
                valueValueString = r_valueValueString;
            }

            // fill structure
            field.key.type = keyTypeString;
            field.key.name = keyNameString;

            field.value.type  = valueTypeString;
            field.value.value = valueValueString;

            return(field);
        }
예제 #29
0
 public HashingTest()
 {
     this._hashParameters = new HashParameters(10, this.GenerateSalt());
     this._stringHasher   = new StringHasher(this._hashParameters);
 }
예제 #30
0
 public AuthResult Authenticate(User user, string password)
 {
     return(user?.PasswordHash == StringHasher.Get(password) ? AuthResult.Success : AuthResult.InvalidPassword);
 }