Example #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));
            }
        }
Example #2
0
        static HttpResponse GetStudyResultsProcessor(IHttpHeaders query, Account account)
        {
            if (account.Approved)
            {
                if (account.AccountType == AccountType.Student)
                {
                    var range = DBHolderSQL.GetRange(nameof(StatementResult), null, -1, -1, true, false, false, false, (nameof(StatementResult.StudentID), account.ID));
                    range.Columns.Add(nameof(StatementResult.SubjectName_STUDENT_MODE));
                    foreach (DataRow current in range.Rows)
                    {
                        current[nameof(StatementResult.SubjectName_STUDENT_MODE)] = DBHolderSQL.GetByID(nameof(Subject), (int)(long)current[nameof(StatementResult.SubjectID)])[nameof(Subject.SubjectName)];
                    }

                    return(new HttpResponse(HttpResponseCode.Ok, JsonConvert.SerializeObject(range, new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore
                    }), true));
                }
                else
                {
                    return(new HttpResponse(HttpResponseCode.BadRequest, "Увы, это доступно только для студентов.", false));
                }
            }
            else
            {
                return(new HttpResponse(HttpResponseCode.Forbidden, "Аккаунт не подтвержден!", false));
            }
        }
Example #3
0
        public Task Handle(IHttpContext context, Func <Task> next)
        {
            var request = context.Request;

            if (request.Method == HttpMethods.Post)
            {
                if (request.Post.Parsed.TryGetByName("token", out string tokenString))
                {
                    var validationResult = AuthorizationHandler.VerifyToken(tokenString, false);
                    if (validationResult.valid)
                    {
                        if ((DateTime.Now.Subtract(validationResult.account.LastAction ?? new DateTime()).TotalSeconds) > Account.OnlineTimeoutSeconds - 1)
                        {
                            validationResult.account.LastAction = DateTime.Now;
                            DBHolderSQL.Save(nameof(Account), (nameof(Account.ID), validationResult.account.ID), (nameof(Account.LastAction), validationResult.account.LastAction));
                        }
                        if (request.Post.Parsed.TryGetByName("action", out string action))
                        {
                            context.Response = Actions[action]?.Invoke(request.Post.Parsed, validationResult.account);
                        }
                        else
                        {
                            context.Response = new HttpResponse(HttpResponseCode.MethodNotAllowed, "Эм.. что от меня требуется???", false);
                        }
                    }
                    else
                    {
                        DBHolderSQL.Log($"[ОШИБКА ДОСТУПА] Пользователь с поврежденным или подделанным токеном пытался войти в систему. Экземпляр токена предоставлен в описании.",
                                        $"{tokenString}");
                        context.Response = new HttpResponse(HttpResponseCode.Forbidden, "Доступ запрещен! Ошибка разбора токена!", false);
                    }
                }
                else
                {
                    context.Response = new HttpResponse(HttpResponseCode.Forbidden, "Доступ запрещен! Нужен токен!", false);
                }
            }
            else
            {
                context.Response = new HttpResponse(HttpResponseCode.MethodNotAllowed, "Метод недоступен!", false);
            }

            return(Task.Factory.GetCompleted());
        }
Example #4
0
        public static (bool valid, object account) VerifyToken(string tokenString, bool deSerializeAccount, bool wipePassword)
        {
            var data = GetToken(tokenString);

            if (data.id == -1 || string.IsNullOrWhiteSpace(data.userName))
            {
                return(false, null);
            }

            DataTable table = DBHolderSQL.GetRange("Account", null, 0, 1, true, false, false, false,
                                                   ("ID", data.id),
                                                   ("UserName", data.userName == "_default_" ? string.Empty : data.userName),
                                                   ("Password", data.password == "_default_" ? string.Empty : data.password));

            if (table.Rows.Count == 1)
            {
                if (wipePassword)
                {
                    table.Rows[0]["Password"] = null;
                }
                return(true, deSerializeAccount ?
                       (object)new Account
                {
                    ID = (int)(long)table.Rows[0]["ID"],
                    AccountType = (AccountType)(int)(long)table.Rows[0]["AccountType"],
                    Approved = ((long)table.Rows[0]["Approved"] == 1),
                    LastAction = table.Rows[0]["LastAction"] == DBNull.Value ? null : (DateTime?)table.Rows[0]["LastAction"],
                    Password = table.Rows[0]["Password"] == DBNull.Value ? null : (string)table.Rows[0]["Password"],
                } :
                       JsonConvert.SerializeObject(table, new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));
            }
            else if (table.Rows.Count > 1)
            {
                return(false, null);
            }
            else
            {
                return(false, null);
            }
        }
Example #5
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);
        }
Example #6
0
        public static void Main()
        {
            foreach (var current in Enum.GetValues(typeof(ConsoleColor)))
            {
                PrintLogo((ConsoleColor)current);
                Thread.Sleep(50);
                Console.CursorLeft = Console.CursorTop = 0;
            }
            PrintLogo(ConsoleColor.Green);

            Console.WriteLine("Welcome to InCollege.Server! Don't hesitate, open http://localhost/ to see what we got!");
            Console.WriteLine("Made by [CYBOR] = Muhametshin R.A.");

            Console.WriteLine($"Initializing SQLite DB(thanks Frank A. Krueger and other 53 team members for sqlite-net engine) in \n{CommonVariables.DBLocation}...\n");
            bool createAdmin = !File.Exists(CommonVariables.DBLocation);

            DBHolderSQL.Init(CommonVariables.DBLocation);
            if (createAdmin)
            {
                DBHolderSQL.Save(nameof(Account), new Account
                {
                    FullName    = "Администратор",
                    UserName    = "******",
                    AccountType = AccountType.Admin,
                    Approved    = true
                }.Columns.ToArray());
            }

            Console.WriteLine($"Initializing uHttpSharp server engine(thanks Elad Zelingher and other 6 team members for uHttpSharp engine)...");
            InCollegeServer.Start();

            while (true)
            {
                Thread.Sleep(1000);
            }
        }