예제 #1
0
        public void Process()
        {
            HttpListenerRequest  request  = context.Request;
            HttpListenerResponse response = context.Response;

            Stream       streamBody   = request.InputStream;
            Encoding     encoding     = request.ContentEncoding;
            StreamReader streamReader = new StreamReader(streamBody, encoding);
            var          sRequest     = streamReader.ReadToEnd();

            AuthorizedUser user           = new AuthorizedUser(request.Headers["login"], request.Headers["Authorization"]);
            var            userDb         = CRUD.GetUser(user);
            string         responseString = "";
            string         stateString    = "";

            //if (userDb == null)
            //{
            //    /*user.Id = userDb.Id;
            //    var sessionDb = CRUD.GetSession(user);
            //    sessionDb.SessionKey = user.GetSessionKey();
            //    CRUD.SetSession(sessionDb);*/
            //    CRUD.CreateUser(user);
            //    responseString = $"Пользователь зарегистрирован Логин={user.Login}, Hash={user.Hash}, Session={user.SessionKey}";
            //}
            //else
            //{
            //    responseString = $"Ошибка регистрации, пользователь уже зарегистрирован Логин={user.Login}, Hash={user.Hash}";
            //}

            switch (request.HttpMethod)
            {
            case "GET":
                Login(userDb, user, out responseString);
                break;

            case "POST":
                Reg(userDb, user, out responseString);
                break;

            case "DELETE":
                Delete(userDb, user, out responseString);
                break;

            default:
                responseString = $"Ошибка, не распознан HTTP метод";
                break;
            }
            stateString = $"Login = {user.Login}\nHash = {user.Hash}\nSession = {user.SessionKey}\nDateOff = {user.DateOff}\nSessionExpTime = {user.ExpTime}\n\n";
            Console.WriteLine(stateString);


            //Console.WriteLine($"{request.HttpMethod} {sRequest} {request.Headers} {request.UserAgent}");

            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;

            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }
예제 #2
0
파일: CRUD.cs 프로젝트: astral-team/HR-tool
        /// <summary>
        /// Смена пароля
        /// </summary>
        public static void ChangePassword(AuthorizedUser user)
        {
            var userDB = GetUser(user);

            if (userDB != null)
            {
                dbContext.Entry(userDB).State = EntityState.Modified;
                dbContext.SaveChanges();
            }
        }
예제 #3
0
 private static void Reg(Logins userDb, AuthorizedUser user, out string responseString)
 {
     if (userDb == null)
     {
         CRUD.CreateUser(user);
         responseString = "200";
     }
     else
     {
         responseString = "404";
     }
 }
예제 #4
0
 private static void Delete(Logins userDb, AuthorizedUser user, out string responseString)
 {
     if (userDb != null)
     {
         userDb.DateOff = DateTime.Now;
         CRUD.RemoveUser(userDb);
         responseString = "200";
     }
     else
     {
         responseString = "404";
     }
 }
예제 #5
0
파일: CRUD.cs 프로젝트: astral-team/HR-tool
 public static Session GetSession(AuthorizedUser user)
 {
     //return dbContext.UserDBSet.AsQueryable<UserDB>();
     // Используем LINQ-запрос для извлечения данных
     try
     {
         return(dbContext.SessionSet.AsQueryable().Where(x => x.LoginId == user.Id).First());
     }
     catch
     {
         return(null);
     }
 }
예제 #6
0
파일: CRUD.cs 프로젝트: astral-team/HR-tool
 /// <summary>
 /// Получение пользователя из базы данных, если его нет возвращается null
 /// </summary>
 public static Logins GetUser(AuthorizedUser user)
 {
     //return dbContext.UserDBSet.AsQueryable<UserDB>();
     // Используем LINQ-запрос для извлечения данных
     try
     {
         return(dbContext.LoginsSet.AsQueryable().Where(x => x.DateOff == DateTimeOffset.MinValue).Where(x => x.Login == user.Login).First());
     }
     catch
     {
         return(null);
     }
 }
예제 #7
0
파일: CRUD.cs 프로젝트: astral-team/HR-tool
        /// <summary>
        /// Создание нового пользователя
        /// </summary>
        public static bool CreateUser(AuthorizedUser user)
        {
            Logins userdb = new Logins()
            {
                Id = Guid.NewGuid()
            };

            CreateSession(userdb.Id);
            userdb.Login = user.Login;
            userdb.Hash  = user.Hash;

            //dbContext.UserDBSet.Add(user.ToUserDB());
            dbContext.LoginsSet.Add(userdb);
            dbContext.SaveChanges();
            return(true);
        }
예제 #8
0
 private static void Login(Logins userDb, AuthorizedUser user, out string responseString)
 {
     if (userDb != null)
     {
         user.Id = userDb.Id;
         var sessionDb = CRUD.GetSession(user);
         sessionDb.SessionKey = user.GetSessionKey();
         sessionDb.ExpTime    = DateTime.Now.AddMinutes(10);
         user.ExpTime         = sessionDb.ExpTime;
         CRUD.SetSession(sessionDb);
         responseString = $"{user.SessionKey}";
     }
     else
     {
         responseString = "404";
     }
 }
예제 #9
0
        public void Process()
        {
            HttpListenerRequest  request  = context.Request;
            HttpListenerResponse response = context.Response;

            Stream streamBody = request.InputStream;

            Encoding     encoding     = Encoding.UTF8;
            StreamReader streamReader = new StreamReader(streamBody, encoding);
            var          sRequest     = streamReader.ReadToEnd();

            var profile = JsonConvert.DeserializeObject <List <ProfileData> >(sRequest);

            AuthorizedUser user           = new AuthorizedUser(request.Headers["login"], request.Headers["Authorization"]);
            var            userDb         = CRUD.GetUser(user);
            string         responseString = "";
            string         stateString    = "";

            if (userDb != null)
            {
                user.Id = userDb.Id;
            }

            var sessionDb = CRUD.GetSession(user);

            switch (request.HttpMethod)
            {
            case "GET":
                if (Validator.CheckTimeOfSession(sessionDb))
                {
                    GetProf(out responseString);
                }
                else
                {
                    responseString = $"Ошибка, неверный сессионный ключ, Логин={user.Login}, Hash={user.Hash}";
                }
                break;

            case "POST":
                if (Validator.CheckTimeOfSession(sessionDb))
                {
                    AddProfile(profile, out responseString);
                }
                else
                {
                    responseString = $"Ошибка, неверный сессионный ключ, Логин={user.Login}, Hash={user.Hash}";
                }
                break;

            case "DELETE":
                if (Validator.CheckTimeOfSession(sessionDb))
                {
                    Delete(profile, out responseString);
                }
                else
                {
                    responseString = $"Ошибка, неверный сессионный ключ";
                }
                break;

            case "PUT":

                if (Validator.CheckTimeOfSession(sessionDb))
                {
                    Update(profile, out responseString);
                }
                else
                {
                    responseString = $"Ошибка, неверный сессионный ключ";
                }
                break;

            default:
                responseString = $"Ошибка, не распознан HTTP метод";
                break;
            }
            stateString = $"Login = {user.Login}\nHash = {user.Hash}\n\n";
            Console.WriteLine(stateString);

            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;

            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }