Beispiel #1
0
        private static IHttpResponse SignIn(IHttpHeaders query)
        {
            if (query.TryGetByName("UserName", out string userName) &&
                query.TryGetByName("Password", out string password))
            {
                var rows = DBHolderSQL.GetRange("Account", null, 0, 1, true, false, false, false,
                                                ("UserName", userName),
                                                ("Password", password)).Rows;

                if (rows.Count == 1)
                {
                    return(new HttpResponse(HttpResponseCode.Ok, CreateToken(int.Parse(rows[0]["ID"].ToString()), userName, password), true));
                }
                else if (rows.Count > 1)
                {
                    DBHolderSQL.Log($"[КОНФЛИКТ] Конфликт аккаунтов {userName}.",
                                    $"Попытка входа при наличии более одного аккаунта с одинаковым именем пользователя ({userName}).\n" +
                                    $"Измените имя пользователя для одного из аккаунтов.");
                    return(new HttpResponse(HttpResponseCode.InternalServerError, "Ошибка! Найдено более 1 аккаунта. Обратитесь к администратору.", false));
                }
                else
                {
                    DBHolderSQL.Log($"[НЕВЕРНЫЙ ВВОД] Ошибка авторизации пользователя {userName}.",
                                    $"Пользователь ввел неверные данные. Осторожно! Это может означать попытку взлома \"Грубой силой\"(BruteForce)");
                    return(new HttpResponse(HttpResponseCode.Forbidden, "Ошибка! Пользователь с таким именем пользователя и паролем не найден.", false));
                }
            }
            else
            {
                return(new HttpResponse(HttpResponseCode.Forbidden, "Укажите 'UserName' и 'Password'!", false));
            }
        }
        public static bool KeepAliveConnection(this IHttpHeaders headers)
        {
            string value;

            return(headers.TryGetByName("connection", out value) &&
                   value.Equals("Keep-Alive", StringComparison.InvariantCultureIgnoreCase));
        }
        public static T GetByName <T>(this IHttpHeaders headers, string name)
        {
            T value;

            headers.TryGetByName(name, out value);
            return(value);
        }
Beispiel #4
0
        private object Get(Type type, IHttpHeaders headers, string prefix)
        {
            if (type.IsPrimitive || type == typeof(string))
            {
                string value;
                if (headers.TryGetByName(prefix, out value))
                {
                    return(Convert.ChangeType(value, type));
                }

                return(null);
            }

            var retVal = _activator.Activate(type, null);

            string val;
            var    settedValues =
                retVal.GetType()
                .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                .Where(p => headers.TryGetByName(prefix + "[" + p.Name + "]", out val)).ToList();

            if (settedValues.Count == 0)
            {
                return(null);
            }


            foreach (var prop in settedValues)
            {
                string stringValue;
                if (headers.TryGetByName(prefix + "[" + prop.Name + "]", out stringValue))
                {
                    object value = prop.PropertyType.IsPrimitive || prop.PropertyType == typeof(string)
                        ? Convert.ChangeType(stringValue, prop.PropertyType)
                        : Get(prop.PropertyType, headers, prefix + "[" + prop.Name + "]");

                    prop.SetValue(retVal, value);
                }
            }

            return(retVal);
        }
        public static T GetByNameOrDefault <T>(this IHttpHeaders headers, string name, T defaultValue)
        {
            T value;

            if (headers.TryGetByName(name, out value))
            {
                return(value);
            }

            return(defaultValue);
        }
Beispiel #6
0
 private static IHttpResponse ValidateToken(IHttpHeaders query)
 {
     if (query.TryGetByName("token", out string token))
     {
         return(new HttpResponse(VerifyToken(token, false, true).valid ? HttpResponseCode.Ok : HttpResponseCode.NotAcceptable, string.Empty, false));
     }
     else
     {
         return(new HttpResponse(HttpResponseCode.BadRequest, string.Empty, false));
     }
 }
Beispiel #7
0
        static HttpResponse ChatProcessor(IHttpHeaders query, Account account)
        {
            if (account.Approved)
            {
                if (query.TryGetByName("mode", out byte mode))
                {
                    switch (mode)
                    {
                    case (byte)ChatRequestMode.CheckMessages:

                        (string, object)[] whereParams;
        public static bool TryGetByName <T>(this IHttpHeaders headers, string name, out T value)
        {
            string stringValue;

            if (headers.TryGetByName(name, out stringValue))
            {
                value = (T)Convert.ChangeType(stringValue, typeof(T));
                return(true);
            }

            value = default(T);
            return(false);
        }
Beispiel #9
0
        private static async Task <IHttpPost> GetPostData(IStreamReader streamReader, IHttpHeaders headers)
        {
            int       postContentLength;
            IHttpPost post;

            if (headers.TryGetByName("content-length", out postContentLength) && postContentLength > 0)
            {
                post = await HttpPost.Create(streamReader, postContentLength, Logger).ConfigureAwait(false);
            }
            else
            {
                post = EmptyHttpPost.Empty;
            }
            return(post);
        }
 private static async Task<byte[]> GetPostData(HttpStreamReader streamReader, IHttpHeaders headers)
 {
     int postContentLength;
     byte[] post;
     if (headers.TryGetByName("content-length", out postContentLength))
     {
         byte[] buffer = new byte[postContentLength];
         var readBytes = await streamReader.BaseStream.ReadAsync(buffer, 0, postContentLength);
         post = buffer;
     }
     else
     {
         post = null;
     }
     return post;
 }
Beispiel #11
0
        private static async Task <IHttpPost> GetPostData(IStream s, IHttpHeaders headers)
        {
            IHttpPost post;

            if (headers.TryGetByName("content-length", out int postContentLength) && postContentLength > 0)
            {
                var buffer = new ArraySegment <byte>(new byte[postContentLength]);
                await s.ReadAsync(buffer).ConfigureAwait(false);

                post = new HttpPost(buffer.ToArray());
            }
            else
            {
                post = EmptyHttpPost.Empty;
            }

            return(post);
        }
Beispiel #12
0
 private static IHttpResponse WhoAmI(IHttpHeaders arg)
 {
     if (arg.TryGetByName("token", out string tokenString))
     {
         //Nope! I won't send password with account info!
         var token = VerifyTokenString(tokenString, true);
         if (token.valid)
         {
             return(new HttpResponse(HttpResponseCode.Ok, token.accountJSON, true));
         }
         else
         {
             return(new HttpResponse(HttpResponseCode.Forbidden, "Токен невалидный. Проверьте правильность или запросите новый.", false));
         }
     }
     else
     {
         return(new HttpResponse(HttpResponseCode.Forbidden, "Не удалось получить данные об аккаунте. Нужен токен!", false));
     }
 }
Beispiel #13
0
        public T Get <T>(IHttpHeaders headers)
        {
            var retVal = _activator.Activate <T>(null);

            foreach (var prop in retVal.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (prop.PropertyType.IsPrimitive || prop.PropertyType == typeof(string))
                {
                    string stringValue;
                    if (headers.TryGetByName(prop.Name, out stringValue))
                    {
                        var value = Convert.ChangeType(stringValue, prop.PropertyType);
                        prop.SetValue(retVal, value);
                    }
                }
                else
                {
                    var value = Get(prop.PropertyType, headers, prop.Name);
                    prop.SetValue(retVal, value);
                }
            }

            return(retVal);
        }
Beispiel #14
0
        private static IHttpResponse SignUp(IHttpHeaders query)
        {
            if (query.TryGetByName("UserName", out string userName) &&
                query.TryGetByName("Password", out string password) &&
                query.TryGetByName("AccountType", out byte accountType) &&
                query.TryGetByName("BirthDate", out string birthDateString) &&
                DateTime.TryParseExact(birthDateString, Core.CommonVariables.DateFormatString, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime birthDate) &&

                query.TryGetByName("FullName", out string fullName))
            {
                var validationResult = Account.Validate(userName, password, birthDate, fullName);
                if (validationResult == AccountValidationResult.OK)
                {
                    var rows = DBHolderSQL.GetRange("Account", null, 0, 1, true, false, false, false, ("UserName", userName)).Rows;
                    if (rows.Count == 0)
                    {
                        query.TryGetByName("ProfileImage", out byte[] profileImage);
                        return(new HttpResponse(HttpResponseCode.Ok, CreateToken(DBHolderSQL.Save("Account",
                                                                                                  ("UserName", userName),
                                                                                                  ("Password", password),
                                                                                                  ("AccountType", accountType),
                                                                                                  ("BirthDate", birthDate),
                                                                                                  ("ProfileImage", profileImage),
                                                                                                  ("FullName", fullName),
                                                                                                  ("Approved", false),
                                                                                                  ("IsLocal", true),
                                                                                                  ("ID", -1)),
                                                                                 userName, password), true));
                    }
                    else
                    {
                        return(new HttpResponse(HttpResponseCode.BadRequest, "Ошибка! Регистрация невозможна, т.к. пользователь с этим именем пользователя уже зарегистирован в системе!", false));
                    }
                }
                else
                {
                    return(new HttpResponse(HttpResponseCode.BadRequest, ErrorMessages[validationResult], false));
                }
            }
            return(null);
        }
 private static async Task<IHttpPost> GetPostData(IStreamReader streamReader, IHttpHeaders headers)
 {
     int postContentLength;
     IHttpPost post;
     if (headers.TryGetByName("content-length", out postContentLength) && postContentLength > 0)
     {
         post = await HttpPost.Create(streamReader, postContentLength, Logger).ConfigureAwait(false);
     }
     else
     {
         post = EmptyHttpPost.Empty;
     }
     return post;
 }