Beispiel #1
0
        public Guid AddUser(int userId)
        {
            Guid key = Guid.NewGuid();

            LoggedUsers.Add(key, userId);
            return(key);
        }
        public IHttpActionResult GetDriver([FromUri] string senderID, [FromUri] string userIdToGet)
        {
            Driver result = null;

            if (!LoggedUsers.Contains(senderID))
            {
                return(Content(HttpStatusCode.Unauthorized, "Not logged in."));
            }

            try
            {
                if (DbDriver.Exists(userIdToGet))
                {
                    if (!DbAdmin.Exists(senderID) || senderID != userIdToGet)
                    {
                        return(Content(HttpStatusCode.Unauthorized, "Not a dispatcher nor the user whose information are requested."));
                    }

                    result = DbDriver.GetSingleEntityByKey(userIdToGet);
                }
            }
            catch (Exception e)
            {
                Trace.Write($"Error on 'GetDriver()'. Error message: {e.Message}");
                Trace.Write($"[STACK_TRACE] {e.StackTrace}");
                return(InternalServerError(e));
            }

            if (result == null)
            {
                return(NotFound());
            }

            return(Ok(result));
        }
        public IHttpActionResult GetUsers([FromUri] string senderID)
        {
            List <IUser> result = new List <IUser>();

            if (!LoggedUsers.Contains(senderID))
            {
                return(Content(HttpStatusCode.Unauthorized, "Not logged in."));
            }

            //other rights?

            try
            {
                (DbAdmin.GetAll()).ToList().ForEach(a => result.Add(a));
                (DbCustomer.GetAll()).ToList().ForEach(c => result.Add(c));
                (DbDriver.GetAll()).ToList().ForEach(d => result.Add(d));
            }
            catch (Exception e)
            {
                Trace.Write($"Error on 'GetUsers()'. Error message: {e.Message}");
                Trace.Write($"[STACK_TRACE] {e.StackTrace}");
                return(InternalServerError(e));
            }

            return(Ok(result));
        }
        public IHttpActionResult GetPage([FromUri] string senderID)
        {
            if (!LoggedUsers.Contains(senderID))
            {
                return(Content(HttpStatusCode.Unauthorized, "Not logged in."));
            }

            try
            {
                if (DbAdmin.Exists(senderID))
                {
                    return(Ok("./Content/partials/adminProfile.html"));
                }
                else if (DbDriver.Exists(senderID))
                {
                    return(Ok("./Content/partials/driverProfile.html"));
                }
                else if (DbCustomer.Exists(senderID))
                {
                    return(Ok("./Content/partials/customerProfile.html"));
                }
                else
                {
                    return(NotFound());
                }
            }
            catch (Exception e)
            {
                Trace.Write($"Error on 'Login()'. Error message: {e.Message}");
                Trace.Write($"[STACK_TRACE] {e.StackTrace}");
                return(InternalServerError(e));
            }
        }
Beispiel #5
0
        public void LoggedUsers_GetUser()
        {
            var loggedUsers = LoggedUsers.GetInstance();
            var user1       = new UserFactory().CreateAdmin(new User
            {
                Id       = 21,
                Login    = "******",
                Password = new Encryption.HasherFactory().GetHasher().Hash("Pass"),
                Rank     = Rank.Administrator
            });

            var(_, token1) = loggedUsers.LogInUser(user1);
            var user2 = new UserFactory().CreateStudent(new User
            {
                Id       = 22,
                Login    = "******",
                Password = new Encryption.HasherFactory().GetHasher().Hash("Pass1"),
                Rank     = Rank.Student
            }, new StudentData());

            var(_, token2) = loggedUsers.LogInUser(user2);
            // pobranie User1
            Assert.IsTrue(Object.ReferenceEquals(user1, loggedUsers.GetUser(token1)));
            // pobranie User2
            Assert.IsTrue(Object.ReferenceEquals(user2, loggedUsers.GetUser(token2)));

            loggedUsers.LogOutUser(token1);
            loggedUsers.LogOutUser(token2);
            // pobranie User1
            Assert.IsFalse(Object.ReferenceEquals(user1, loggedUsers.GetUser(token1)));
            // pobranie User2 - niezalogowanyt
            Assert.IsFalse(Object.ReferenceEquals(user2, loggedUsers.GetUser(token2)));
        }
Beispiel #6
0
        /// <summary>
        /// Checks if specific user is already logged.
        /// </summary>
        /// <param name="login">User login to check</param>
        /// <returns>True if user login is already used, false otherwise.</returns>
        public static bool IsUserAlreadyLogged(ChatUser user)
        {
            lock (locker)
            {
                var result = LoggedUsers.Contains(user, new ChatUserComparerByLogin());

                return(result);
            }
        }
        public void Broker_Update(object sender, EventArgs e)
        {
            var users = userRepo.GetAllLoggedUser().ToList();

            App.Current.Dispatcher.Invoke((Action) delegate // <--- HERE
            {
                LoggedUsers.Clear();
                users.ForEach(user => LoggedUsers.Add(user));
            });
        }
        public IHttpActionResult PostCustomer([FromUri] string senderID, [FromBody] GeneralUserModel userModel)
        {
            Customer customer = new Customer(userModel.Username, userModel.Password)
            {
                FirstName = userModel.FirstName,
                LastName  = userModel.LastName,
                Gender    = userModel.Gender,
                JMBG      = userModel.JMBG,
                Phone     = userModel.Phone,
                Email     = userModel.Email,
            };

            userModel.TaxiDrivesIDs.ForEach(td => customer.TaxiDrives.Add(DbTaxiDrive.GetSingleEntityByKey(td)));

            //Customer ne pravi sam svoj nalog
            if (senderID != customer.Username)
            {
                if (!LoggedUsers.Contains(senderID))
                {
                    return(Content(HttpStatusCode.Unauthorized, "Not logged in."));
                }
                else if (!DbAdmin.Exists(senderID))
                {
                    return(Content(HttpStatusCode.Unauthorized, "Not a dispatcher nor the user to be added."));
                }
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            bool result;

            try
            {
                result = DbCustomer.Add(customer);
            }
            catch (Exception e)
            {
                Trace.Write($"Error on 'PostCustomer()'. Error message: {e.Message}");
                Trace.Write($"[STACK_TRACE] {e.StackTrace}");
                return(InternalServerError(e));
            }

            if (result)
            {
                return(Ok(customer));
            }
            else
            {
                return(BadRequest("Customer already exists."));
            }
        }
Beispiel #9
0
        private void RefreshConnectedUsers()
        {
            List <string> connectedStudents = LoggedUsers.GetUsers("student").ToList();

            StudentCount.Text      = connectedStudents.Count.ToString();
            StudentList.DataSource = connectedStudents;

            List <string> connectedTeachers = LoggedUsers.GetUsers("teacher", "teacher_admin").ToList();

            TeacherCount.Text      = connectedTeachers.Count.ToString();
            TeacherList.DataSource = connectedTeachers;
        }
 public IHttpActionResult Logout([FromBody] LogoutModel logoutModel)
 {
     if (!LoggedUsers.Contains(logoutModel.Username))
     {
         return(BadRequest($"User '{logoutModel.Username}' was not logged in."));
     }
     else
     {
         LoggedUsers.Remove(logoutModel.Username);
         return(Ok());
     }
 }
        public IHttpActionResult PostDriver([FromUri] string senderID, [FromBody] DriverModel driverModel)
        {
            Driver driver = new Driver(driverModel.Username, driverModel.Password)
            {
                FirstName       = driverModel.FirstName,
                LastName        = driverModel.LastName,
                Gender          = driverModel.Gender,
                JMBG            = driverModel.JMBG,
                Phone           = driverModel.Phone,
                Email           = driverModel.Email,
                DriversLocation = DbLocation.GetSingleEntityByKey(driverModel.DriversLocationID),
                DriversVehicle  = DbVehicle.GetSingleEntityByKey(driverModel.DriversVehicleID),
            };

            driverModel.TaxiDrivesIDs.ForEach(td => driver.TaxiDrives.Add(DbTaxiDrive.GetSingleEntityByKey(td)));

            if (!LoggedUsers.Contains(senderID))
            {
                return(Content(HttpStatusCode.Unauthorized, "Not logged in."));
            }
            else if (!DbAdmin.Exists(senderID))
            {
                return(Content(HttpStatusCode.Unauthorized, "Not a dispatcher."));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            bool result;

            try
            {
                result = DbDriver.Add(driver);
            }
            catch (Exception e)
            {
                Trace.Write($"Error on 'PostDriver()'. Error message: {e.Message}");
                Trace.Write($"[STACK_TRACE] {e.StackTrace}");
                return(InternalServerError(e));
            }

            if (result)
            {
                return(Ok(driver));
            }
            else
            {
                return(BadRequest("Driver already exists."));
            }
        }
        // PUT api/drivers/5
        public IHttpActionResult PutDriver([FromUri] string senderID, [FromBody] DriverModel driverModel)
        {
            bool result = false;

            if (!LoggedUsers.Contains(senderID))
            {
                return(Content(HttpStatusCode.Unauthorized, "Not logged in."));
            }

            if (DbDriver.Exists(driverModel.Username))
            {
                if (!DbAdmin.Exists(senderID) || senderID != driverModel.Username)
                {
                    return(Content(HttpStatusCode.Unauthorized, "Not a dispatcher nor a user to be modified."));
                }


                try
                {
                    Driver driver = new Driver(driverModel.Username, driverModel.Password)
                    {
                        FirstName       = driverModel.FirstName,
                        LastName        = driverModel.LastName,
                        Gender          = driverModel.Gender,
                        JMBG            = driverModel.JMBG,
                        Phone           = driverModel.Phone,
                        Email           = driverModel.Email,
                        DriversLocation = DbLocation.GetSingleEntityByKey(driverModel.DriversLocationID),
                        DriversVehicle  = DbVehicle.GetSingleEntityByKey(driverModel.DriversVehicleID),
                    };
                    driverModel.TaxiDrivesIDs.ForEach(td => driver.TaxiDrives.Add(DbTaxiDrive.GetSingleEntityByKey(td)));

                    result = DbDriver.Modify(driver);
                }
                catch (Exception e)
                {
                    Trace.Write($"Error on 'PutDriver()'. Error message: {e.Message}");
                    Trace.Write($"[STACK_TRACE] {e.StackTrace}");
                    return(InternalServerError(e));
                }
            }

            if (result)
            {
                return(Ok(driverModel));
            }
            else
            {
                return(NotFound());
            }
        }
        public IHttpActionResult Login([FromBody] LoginModel loginModel)
        {
            if (LoggedUsers.Contains(loginModel.Username))
            {
                return(Content(HttpStatusCode.Conflict, $"User '{loginModel.Username}' already logged in."));
            }

            IUser result = null;

            try
            {
                if (DbAdmin.Exists(loginModel.Username))
                {
                    result = DbAdmin.GetSingleEntityByKey(loginModel.Username);
                }
                else if (DbDriver.Exists(loginModel.Username))
                {
                    result = DbDriver.GetSingleEntityByKey(loginModel.Username);
                }
                else if (DbCustomer.Exists(loginModel.Username))
                {
                    result = DbCustomer.GetSingleEntityByKey(loginModel.Username);
                }
            }
            catch (Exception e)
            {
                Trace.Write($"Error on 'Login()'. Error message: {e.Message}");
                Trace.Write($"[STACK_TRACE] {e.StackTrace}");
                return(InternalServerError(e));
            }

            if (result == null)
            {
                return(NotFound());
            }

            if (result.Password.Equals(loginModel.Password))
            {
                LoggedUsers.Add(loginModel.Username);
                return(Ok(result));
            }
            else
            {
                return(BadRequest($"Entered password did not match the required one for user '{loginModel.Username}'."));
            }
        }
        // DELETE api/drivers/5
        public IHttpActionResult DeleteUser([FromUri] string senderID, [FromUri] string userToDelete)
        {
            bool result = false;

            if (!LoggedUsers.Contains(senderID))
            {
                return(Content(HttpStatusCode.Unauthorized, "Not logged in."));
            }
            else if (!DbAdmin.Exists(senderID))
            {
                return(Content(HttpStatusCode.Unauthorized, "Not a dispatcher."));
            }

            try
            {
                if (DbAdmin.Exists(userToDelete))
                {
                    //TODO: sta ako obrise samog sebe logout?
                    result = DbAdmin.Delete(userToDelete);
                }
                else if (DbDriver.Exists(userToDelete))
                {
                    result = DbDriver.Delete(userToDelete);
                }
                else if (DbCustomer.Exists(userToDelete))
                {
                    result = DbCustomer.Delete(userToDelete);
                }
            }
            catch (Exception e)
            {
                Trace.Write($"Error on 'DeleteUser()'. Error message: {e.Message}");
                Trace.Write($"[STACK_TRACE] {e.StackTrace}");
                return(InternalServerError(e));
            }

            if (result)
            {
                return(Ok());
            }
            else
            {
                return(NotFound());
            }
        }
Beispiel #15
0
        public void LogoutUser_UserNotInLoggedUsers()
        {
            var users = new List <User>
            {
                new User
                {
                    Id       = 1,
                    Login    = "******",
                    Password = new Encryption.HasherFactory().GetHasher().Hash("Admin"),
                    Rank     = Rank.Administrator
                }
            };

            var mockSet     = CreateNewMockSetWithData(users);
            var mockContext = new Mock <DatabaseContext>();

            mockContext.Setup(m => m.Set <User>()).Returns(mockSet.Object);

            var oldDb = RepositoryFactory.SetDbContext(mockContext.Object);

            var loginDict = new Dictionary <string, string>
            {
                ["login"]    = "******",
                ["password"] = "******",
            };

            var userController = new UserController();

            var(loggedInAdmin, tokenAdmin) = userController.LogIn(loginDict);

            userController.LogOut(tokenAdmin);

            var user = LoggedUsers.GetInstance().GetUser(tokenAdmin);

            Assert.IsTrue(user == null);

            RepositoryFactory.SetDbContext(oldDb);
        }
Beispiel #16
0
        public void UserController_CheckRank()
        {
            var loggedUsers = LoggedUsers.GetInstance();
            var user1       = new UserFactory().CreateAdmin(new User
            {
                Id       = 20,
                Login    = "******",
                Password = new Encryption.HasherFactory().GetHasher().Hash("Pass"),
                Rank     = Rank.Administrator
            });

            var(_, token1) = loggedUsers.LogInUser(user1);
            var user2 = new UserFactory().CreateStudent(new User
            {
                Id       = 21,
                Login    = "******",
                Password = new Encryption.HasherFactory().GetHasher().Hash("Pass1"),
                Rank     = Rank.Student
            }, new StudentData());

            var(_, token2) = loggedUsers.LogInUser(user2);

            var userController = new UserController();

            // pobranie rangi User1
            Assert.IsTrue(userController.CheckRank(token1) == Rank.Administrator);
            // pobranie rangi User2
            Assert.IsTrue(userController.CheckRank(token2) == Rank.Student);

            loggedUsers.LogOutUser(token1);
            loggedUsers.LogOutUser(token2);
            // pobranie rangi wylogowanego użytkownika User1
            Assert.IsTrue(userController.CheckRank(token1) == Rank.None);
            // pobranie rangi wylogowanego użytkownika User2
            Assert.IsTrue(userController.CheckRank(token2) == Rank.None);
        }
Beispiel #17
0
        public void CourseGroup_EditCoursesGroup()
        {
            var loggedUsers = LoggedUsers.GetInstance();
            var user1       = new UserFactory().CreateAdmin(new User
            {
                Id       = 20,
                Login    = "******",
                Password = new Encryption.HasherFactory().GetHasher().Hash("Pass"),
                Rank     = Rank.Administrator
            });

            var(_, tokenAdmin) = loggedUsers.LogInUser(user1);
            var user2 = new UserFactory().CreateStudent(new User
            {
                Id       = 21,
                Login    = "******",
                Password = new Encryption.HasherFactory().GetHasher().Hash("Pass1"),
                Rank     = Rank.Student
            }, new StudentData());

            var(_, tokenStudent) = loggedUsers.LogInUser(user2);
            var field = new Field {
                Id = 1, Name = "Inf"
            };
            var fields = new List <Field> {
                field
            };
            var courseGroup = new CourseGroup {
                Id = 1, Field = field, FieldId = field.Id
            };
            var courseGroups = new List <CourseGroup> {
                courseGroup
            };

            var mockContext = new Mock <DatabaseContext>();

            var mockSetFields = CreateNewMockSetWithData(fields);

            mockContext.Setup(m => m.Set <Field>()).Returns(mockSetFields.Object);
            var mockSetCG = CreateNewMockSetWithData(courseGroups);

            mockContext.Setup(m => m.Set <CourseGroup>()).Returns(mockSetCG.Object);

            var oldDb = RepositoryFactory.SetDbContext(mockContext.Object);


            var rightData = new Dictionary <string, string>
            {
                ["id"]       = "1",
                ["ects"]     = "29",
                ["semester"] = "6",
                ["fieldId"]  = "1",
                ["code"]     = "INEK000420",
                ["name"]     = "Analiza matematyczna 4",
            };
            var cgController = new CourseGroupController();

            // nieprawidłowy użytkownik
            var(result, _) = cgController.EditCoursesGroup(rightData, tokenStudent);
            Assert.IsFalse(result);
            // niezalogowany użytkownik
            (result, _) = cgController.EditCoursesGroup(rightData, "");
            Assert.IsFalse(result);
            // Nieprawidłowe Id grupy kursów
            var badData = new Dictionary <string, string>(rightData);

            badData["id"] = "2";
            (result, _)   = cgController.EditCoursesGroup(badData, tokenAdmin);
            Assert.IsFalse(result);
            // Nieprawidłowe ects
            badData         = new Dictionary <string, string>(rightData);
            badData["ects"] = "asd";
            (result, _)     = cgController.EditCoursesGroup(badData, tokenAdmin);
            Assert.IsFalse(result);
            badData         = new Dictionary <string, string>(rightData);
            badData["ects"] = "-1";
            (result, _)     = cgController.EditCoursesGroup(badData, tokenAdmin);
            Assert.IsFalse(result);
            // Nieprawidłowy semestr
            badData             = new Dictionary <string, string>(rightData);
            badData["semester"] = "asd";
            (result, _)         = cgController.EditCoursesGroup(badData, tokenAdmin);
            Assert.IsFalse(result);
            badData             = new Dictionary <string, string>(rightData);
            badData["semester"] = "-1";
            (result, _)         = cgController.EditCoursesGroup(badData, tokenAdmin);
            Assert.IsFalse(result);
            // nieprawidłowy kierunek
            badData            = new Dictionary <string, string>(rightData);
            badData["fieldId"] = "asd";
            (result, _)        = cgController.EditCoursesGroup(badData, tokenAdmin);
            Assert.IsFalse(result);
            badData            = new Dictionary <string, string>(rightData);
            badData["fieldId"] = "2";
            (result, _)        = cgController.EditCoursesGroup(badData, tokenAdmin);
            Assert.IsFalse(result);
            // pusty kod grupy kursów
            badData         = new Dictionary <string, string>(rightData);
            badData["code"] = "";
            (result, _)     = cgController.EditCoursesGroup(badData, tokenAdmin);
            Assert.IsFalse(result);
            // pusta nazwa grupy kursów
            badData         = new Dictionary <string, string>(rightData);
            badData["name"] = "";
            (result, _)     = cgController.EditCoursesGroup(badData, tokenAdmin);
            Assert.IsFalse(result);
            // prawidłowe
            (result, _) = cgController.EditCoursesGroup(rightData, tokenAdmin);
            Assert.IsTrue(result && courseGroup.Id == Int32.Parse(rightData["id"]) &&
                          courseGroup.NumberOfEcts == Int32.Parse(rightData["ects"]) &&
                          courseGroup.Semester == Int32.Parse(rightData["semester"]) &&
                          Object.ReferenceEquals(courseGroup.Field, field) &&
                          courseGroup.Code == rightData["code"] &&
                          courseGroup.Name == rightData["name"]);

            loggedUsers.LogOutUser(tokenStudent);
            loggedUsers.LogOutUser(tokenAdmin);
            RepositoryFactory.SetDbContext(oldDb);
        }
        // PUT api/drivers/5
        public IHttpActionResult PutNonDriver([FromUri] string senderID, [FromBody] GeneralUserModel user)
        {
            if (!LoggedUsers.Contains(senderID))
            {
                return(Content(HttpStatusCode.Unauthorized, "Not logged in."));
            }

            bool result = false;

            if (DbAdmin.Exists(user.Username))
            {
                if (!DbAdmin.Exists(senderID))
                {
                    return(Content(HttpStatusCode.Unauthorized, "Not a dispatcher."));
                }

                try
                {
                    Admin admin = new Admin(user.Username, user.Password)
                    {
                        FirstName = user.FirstName,
                        LastName  = user.LastName,
                        Gender    = user.Gender,
                        JMBG      = user.JMBG,
                        Phone     = user.Phone,
                        Email     = user.Email,
                    };
                    user.TaxiDrivesIDs.ForEach(td => admin.TaxiDrives.Add(DbTaxiDrive.GetSingleEntityByKey(td)));

                    result = DbAdmin.Modify(admin as Admin);
                }
                catch (Exception e)
                {
                    Trace.Write($"Error on 'PutNonDriver()'. Error message: {e.Message}");
                    Trace.Write($"[STACK_TRACE] {e.StackTrace}");
                    return(InternalServerError(e));
                }
            }
            else if (DbCustomer.Exists(user.Username))
            {
                if (!DbAdmin.Exists(senderID) || senderID != user.Username)
                {
                    return(Content(HttpStatusCode.Unauthorized, "Not a dispatcher nor the user to be modifed."));
                }

                try
                {
                    Customer customer = new Customer(user.Username, user.Password)
                    {
                        FirstName = user.FirstName,
                        LastName  = user.LastName,
                        Gender    = user.Gender,
                        JMBG      = user.JMBG,
                        Phone     = user.Phone,
                        Email     = user.Email,
                    };
                    user.TaxiDrivesIDs.ForEach(td => customer.TaxiDrives.Add(DbTaxiDrive.GetSingleEntityByKey(td)));

                    result = DbCustomer.Modify(customer as Customer);
                }
                catch (Exception e)
                {
                    Trace.Write($"Error on 'PutNonDriver()'. Error message: {e.Message}");
                    Trace.Write($"[STACK_TRACE] {e.StackTrace}");
                    return(InternalServerError(e));
                }
            }

            if (result)
            {
                return(Ok(user));
            }
            else
            {
                return(NotFound());
            }
        }
Beispiel #19
0
 public void LogOut(string token)
 {
     LoggedUsers
     .GetInstance()
     .LogOutUser(token);
 }
Beispiel #20
0
        public (bool, string) SignToLesson(Dictionary <string, string> data, string token)
        {
            var userRank = new UserController().CheckRank(token);

            var loggedUser = LoggedUsers
                             .GetInstance()
                             .GetUser(token);

            var repoFactory = new RepositoryFactory();
            var studentRepo = repoFactory.GetRepository <StudentData>();
            var lessonRepo  = repoFactory.GetRepository <Lesson>();

            int         studentId;
            StudentData student;

            switch (userRank)
            {
            case Rank.None:
                return(false, "Należy się zalogować");

            case Rank.Administrator:
                if (!data.ContainsKey("studentId") || !int.TryParse(data["studentId"], out studentId))
                {
                    return(false, "Niepoprawne ID studenta");
                }
                student = studentRepo.GetDetail(s => s.Id == studentId);
                break;

            default:     // student
                student = (loggedUser as Student).StudentData;
                break;
            }

            if (!data.ContainsKey("lessonId") || !int.TryParse(data["lessonId"], out int lessonId))
            {
                return(false, "Niepoprawne ID zajęć");
            }

            var lesson = lessonRepo.GetDetail(l => l.Id == lessonId);

            if (lesson == null)
            {
                return(false, "Nie ma lekcji o podanym ID");
            }

            var course      = lesson.Course;
            var courseGroup = lesson.Course.CourseGroup;

            var(canSign, err) = new CourseGroupController().CheckPermissions(loggedUser, courseGroup.Id);
            if (!canSign)
            {
                return(false, err);
            }

            if (student.Lessons.Any(l => l.Course == course))
            {
                return(false, "Student jest już zapisany na kurs");
            }

            if (lesson.Space <= 0 && userRank != Rank.Administrator)
            {
                return(false, "Brak miejsc");
            }

            student.Lessons.Add(lesson);
            lesson.Space--;

            studentRepo.SaveChanges();
            lessonRepo.SaveChanges();

            return(true, "Zapis na zajęcia udał się");
        }
        public async Task <IActionResult> LoginMore(LoginModel model)
        {
            string userId     = User.Claims.First(c => c.Type == "UserID").Value;
            var    userLogged = await _userManager.FindByIdAsync(userId);

            try
            {
                var user = await _userManager.FindByNameAsync(model.UserName);

                if (user != null)
                {
                    if (await _userManager.CheckPasswordAsync(user, model.Password))
                    {
                        var tokenDescriptor = new SecurityTokenDescriptor
                        {
                            Subject = new ClaimsIdentity(new Claim[]
                            {
                                new Claim("UserID", user.Id.ToString())
                            }),
                            Expires            = DateTime.UtcNow.AddDays(365),
                            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.JWT_Secret)), SecurityAlgorithms.HmacSha256Signature)
                        };
                        var tokenHandler  = new JwtSecurityTokenHandler();
                        var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                        var token         = tokenHandler.WriteToken(securityToken);
                        var loggedUser    = new LoggedUsers
                        {
                            Id       = user.Id,
                            Email    = user.Email,
                            Name     = user.Name,
                            Surname  = user.Surname,
                            Username = user.UserName,
                            User     = userLogged,
                            UserId   = userLogged.Id
                        };
                        if (userLogged.Id != user.Id)
                        {
                            var isUserLogged = _context.LoggedUsers.Where(x => x.Id == user.Id).FirstOrDefault();
                            if (isUserLogged != null)
                            {
                                return(BadRequest(new { message = "Bu hesapla zaten giriş yapmışsınız." }));
                            }
                            else
                            {
                                await _context.LoggedUsers.AddAsync(loggedUser);

                                await _context.SaveChangesAsync();

                                return(Ok(new { token }));
                            }
                        }
                        else
                        {
                            return(BadRequest(new { message = "Bu hesapla zaten giriş yapmışsınız." }));
                        }
                    }
                    else
                    {
                        return(BadRequest(new { message = "Kullanıcı adı veya şifre yanlış. Lütfen kontrol ediniz" }));
                    }
                }
                else
                {
                    return(BadRequest(new { message = "Böyle bir kullanıcı bulunmamaktadır. Lütfen üye olunuz." }));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }