// GET: api/Login
        public HttpResponseMessage Get()
        {
            try
            {
                var headers = Request.Headers;
                if (headers.Contains("Authorization"))
                {
                    //decode from Base 64
                    string   token  = headers.GetValues("Authorization").First();
                    string[] tokens = token.Split(':');
                    if (tokens.Length == 2)
                    {
                        string userName     = tokens[0];
                        string password     = tokens[1];
                        bool   isValidLogin = UserDBContext.ValidateLogin(userName, password);
                        if (isValidLogin)
                        {
                            return(Request.CreateErrorResponse(HttpStatusCode.OK, "Successful Login"));
                        }
                        else
                        {
                            return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid Login Credentials"));
                        }
                    }
                }

                return(null);
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex));
            }
        }
Exemple #2
0
 public FlBookingsController(FlightDBContext context,
                             UserDBContext userDB, IEmailConfiguration emailConfiguration)
 {
     _context            = context;
     _userDB             = userDB;
     _emailConfiguration = emailConfiguration;
 }
Exemple #3
0
        public ActionResult Login(User user)
        {
            if (String.IsNullOrWhiteSpace(user.Email) || String.IsNullOrWhiteSpace(user.Password))
            {
                return(View(user));
            }

            if (!Helpers.Validations.IsValidEmail(user.Email))
            {
                ModelState.AddModelError("Email", "Email has an invalid format.");

                return(View(user));
            }

            using (UserDBContext db = new UserDBContext())
            {
                User u = db.UserLogin(user.Email, user.Password.ToString());
                if (u != null)
                {
                    Session["UserID"]        = u.id.ToString();
                    Session["UserName"]      = u.Name.ToString();
                    Session["UserPrivilege"] = u.Privilege ? "1" : "0";
                    return(RedirectToAction("Index", "Contents"));
                }
            }

            ModelState.AddModelError("Email", "Email and/or password invalid.");

            return(View(user));
        }
Exemple #4
0
        static void Main(string[] args)
        {
            List <User>     users      = new List <User>();
            List <Category> categories = new List <Category>();

            using (var db = new UserDBContext())
            {
                //db.Database.EnsureDeleted();
                //db.Database.EnsureCreated();

                // add an Item
                // Note autoincrement is on
                //var user = new User()
                //{
                //    Username = "******"
                //};
                //db.Users.Add(user);
                //db.SaveChanges();

                users      = db.Users.Include("Category").ToList();
                categories = db.Categories.ToList();
                users.ForEach(user => Console.WriteLine($"User {user.UserId} {user.Username} has date of birth {user.DateOfBirth} With Category {user.Category.CategoryName}"));
                categories.ForEach(category => Console.WriteLine($"Cat Id {category.CategoryId, -20} Name {category.CategoryName}"));
            }
        }
 public AirBookingsController(AirTaxiDBContext context,
                              UserDBContext userDB, IEmailConfiguration emailConfiguration)
 {
     _context            = context;
     _userDB             = userDB;
     _emailConfiguration = emailConfiguration;
 }
        public HttpResponseMessage PutCustomer(int ID, UserModel user)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            if (ID != user.ID)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "User is not found"));
            }
            UserDBContext  userdb      = new UserDBContext();
            GetAllUsersDTO updateduser = new GetAllUsersDTO();

            updateduser.Address     = user.Address;
            updateduser.Age         = user.Age;
            updateduser.ID          = ID;
            updateduser.Name        = user.Name;
            updateduser.PhoneNumber = user.PhoneNumber;
            updateduser.Gender      = user.Gender;
            var response = userdb.update(ID, updateduser);

            if (response == true)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.OK, "User is updated successfully"));
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "User is not updated"));
            }
        }
Exemple #7
0
        private void AccountDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UserDBContext user = ((UserDBContext)AccountDataGrid.SelectedItem);

            if (user != null)
            {
                EmailAddress.Text = user.Email;
                Password.Password = user.Password;
                UserRole.Text     = user.Role;
                MemberId.Text     = user.MemberID.ToString();
                imgByteArrDB      = user.Image;
                byte[] blob = imgByteArrDB;

                MemoryStream stream = new MemoryStream();
                stream.Write(blob, 0, blob.Length);
                stream.Position = 0;

                System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
                BitmapImage          bi  = new BitmapImage();
                bi.BeginInit();

                MemoryStream ms = new MemoryStream();
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                ms.Seek(0, SeekOrigin.Begin);
                bi.StreamSource = ms;
                bi.EndInit();
                ProfileImage.ImageSource = bi;
            }
        }
 public ActionResult Login(User u)
 {
     //this action is for handle post (login)
     if (ModelState.IsValid)//this checks validity
     {
         using (UserDBContext dc = new UserDBContext())
         {
             var v = dc.Users.Where(a => a.username.Equals(u.username) && a.password.Equals(getMd5Hash(u.password))).FirstOrDefault();
             if (v != null)
             {
                 Session["LogedUserID"]         = v.ID.ToString();
                 Session["LoggedUserFirstname"] = v.firstname.ToString();
                 Session["LoggedUserLastname"]  = v.lastname.ToString();
                 if (v.usertype.Equals("admin"))
                 {
                     return(RedirectToAction("AdminAfterLogin"));
                 }
                 else
                 {
                     return(RedirectToAction("EmployeeAfterLogin"));
                 }
             }
         }
     }
     return(View(u));
 }
        private bool IsUserLoggedIn()
        {
            if (Session["UserID"] == null)
            {
                return(false);
            }

            using (UserDBContext db = new UserDBContext())
            {
                User user = db.GetUserById(Int32.Parse(Session["UserID"].ToString()));

                if (user.id == 0) // User deleted from DB
                {
                    Session["UserID"]        = null;
                    Session["UserName"]      = null;
                    Session["UserPrivilege"] = null;
                    return(false);
                }

                Session["UserID"]        = user.id.ToString();
                Session["UserName"]      = user.Name.ToString();
                Session["UserPrivilege"] = user.Privilege ? "1" : "0";
            }

            return(true);
        }
 public bool IsExist(string Account)
 {
     using (UserDBContext db = new UserDBContext()) {
         string existID = db.AuthAccount.Where(T => T.Account == Account).Select(T => T.ID).FirstOrDefault();
         return(!string.IsNullOrEmpty(existID));
     }
 }
Exemple #11
0
 public static User UserById(int id)
 {
     using (var db = new UserDBContext())
     {
         return(db.Users.Find(id));
     }
 }
        public void AddUserAsyncAddsTheUser()
        {
            using (var context = new UserDBContext(options))
            {
                //Arrange
                IUserRepoDB _repo = new UserRepoDB(context);

                //Act
                _repo.AddUserAsync(
                    new User
                {
                    UserName = "******",
                    Email    = "*****@*****.**",
                    Role     = "Associate"
                }
                    );
            }

            using (var assertContext = new UserDBContext(options))
            {
                //Assert
                var result = assertContext.User.Select(c => c).ToList();

                Assert.NotNull(result);
                Assert.Equal(4, result.Count);
            }
        }
        public ActionResult ViewDB(string DbContext)
        {
            try
            {
                if (!Authen.Certification(Session["UserClass"].ToString(), Authen.UserClass.Admin))
                {
                    return(RedirectToAction("PermitionEr", "Error"));
                }
                HomeworkDBContext       homeworkDB       = new HomeworkDBContext();
                CommentDBContext        commentDB        = new CommentDBContext();
                UserDBContext           userDB           = new UserDBContext();
                CategoryDBContext       categoryDB       = new CategoryDBContext();
                UserCategoriesDBcontext userCategoriesDB = new UserCategoriesDBcontext();
                NoteCatDBContext        noteCatDB        = new NoteCatDBContext();
                ClassNotiDBcontext      classNotiDB      = new ClassNotiDBcontext();



                return(View());
            }
            catch
            {
                return(RedirectToAction("LoginEr", "Error"));
            }
        }
Exemple #14
0
 public static List <User> UserList()
 {
     using (var db = new UserDBContext())
     {
         return(db.Users.OrderBy(p => p.FirstName).ToList());
     }
 }
Exemple #15
0
 public ActionResult Login(User user)
 {
     if (Session["loggedin"] != null && Session["loggedin"].Equals(1))
     {
         return(RedirectToAction("Index", "Home", new { area = "" }));
     }
     else
     {
         using (UserDBContext db = new UserDBContext())
         {
             var usr = db.Users.SingleOrDefault(u => u.Username == user.Username && u.Password == user.Password);
             if (usr != null)
             {
                 Session["loggedin"] = 1;
                 Session["userid"]   = usr.ID;
                 return(RedirectToAction("Index", "Home", new { area = "" }));
             }
             else
             {
                 ViewBag.message = "Username or password incorrect";
                 return(View());
             }
         }
     }
 }
Exemple #16
0
        // GET api/v1/users?name=&&id=
        public async Task <IHttpActionResult> GetUserByNameAndId(string name, string id)
        {
            var result = await Task <UserDTO> .Factory.StartNew(() =>
            {
                UserDTO existingUser = null;
                using (var context = new UserDBContext())
                {
                    var user = context.Users.Where(s => s.UserName == name && s.UserId == id).FirstOrDefault();
                    if (user != null)
                    {
                        existingUser             = new UserDTO();
                        existingUser.UserId      = user.UserId;
                        existingUser.Password    = string.Empty;
                        existingUser.Email       = user.EmailId;
                        existingUser.DisplayName = user.DisplayName;
                        existingUser.UserName    = user.UserName;
                    }
                }

                return(existingUser);
            });

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

            return(Ok(result));
        }
Exemple #17
0
        //DELETE api/v1/users?name=
        public async Task <IHttpActionResult> Delete(string name)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Not a valid model"));
            }

            var updateResult = await Task <bool> .Factory.StartNew(() =>
            {
                bool result = false;
                using (var context = new UserDBContext())
                {
                    var existingUser = context.Users.Where(s => s.UserName == name).FirstOrDefault();
                    if (existingUser != null)
                    {
                        context.Entry(existingUser).State = System.Data.Entity.EntityState.Deleted;
                        context.SaveChanges();
                        result = true;
                    }
                }

                return(result);
            });

            if (updateResult == false)
            {
                return(NotFound());
            }

            return(Ok());
        }
        public void UpdateUserAsyncChangesTheUser()
        {
            using (var context = new UserDBContext(options))
            {
                //Arrange
                IUserRepoDB _repo = new UserRepoDB(context);

                //Act
                _repo.UpdateUserAsync(
                    new User
                {
                    Id       = 1,
                    UserName = "******",
                    Email    = "*****@*****.**",
                    Role     = "Associate"
                }
                    );
            }

            using (var assertContext = new UserDBContext(options))
            {
                //Assert
                var result = assertContext.User.FirstOrDefault(c => c.UserName.Equals("newName"));

                Assert.NotNull(result);
                Assert.Equal(1, result.Id);
            }
        }
Exemple #19
0
 public CarBookingsController(CarRentalDBContext context,
                              UserDBContext userDBContext, IEmailConfiguration emailConfiguration)
 {
     _context            = context;
     _usersDBContext     = userDBContext;
     _emailConfiguration = emailConfiguration;
 }
        private void Seed()
        {
            using (var context = new UserDBContext(options))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();

                context.User.AddRange(
                    new User
                {
                    Id       = 1,
                    UserName = "******",
                    Email    = "*****@*****.**",
                    Role     = "Associate"
                },
                    new User
                {
                    Id       = 2,
                    UserName = "******",
                    Email    = "[email protected]",
                    Role     = "Associate"
                },
                    new User
                {
                    Id       = 3,
                    UserName = "******",
                    Email    = "*****@*****.**",
                    Role     = "The Boss"
                }
                    );

                context.Report.AddRange(
                    new Report
                {
                    UserId      = 1,
                    TargetId    = 10,
                    IsSample    = false,
                    ReportDate  = new DateTime(2021, 01, 31),
                    Description = "Description for test report"
                },
                    new Report
                {
                    UserId      = 2,
                    TargetId    = 20,
                    IsSample    = false,
                    ReportDate  = new DateTime(2021, 02, 14),
                    Description = "Another description for testing"
                },
                    new Report
                {
                    UserId      = 3,
                    TargetId    = 30,
                    IsSample    = true,
                    ReportDate  = new DateTime(2021, 03, 31),
                    Description = "Yet another test description"
                }
                    );
                context.SaveChangesAsync();
            }
        }
Exemple #21
0
 public TokenController(UserDBContext context,
                        IOptions <JwtSettings> optionsAccessor, ITokenManager tokenManager)
 {
     _context      = context;
     _options      = optionsAccessor.Value;
     _tokenManager = tokenManager;
 }
Exemple #22
0
 // GET: Account
 public ActionResult Index()
 {
     using (UserDBContext db = new UserDBContext())
     {
         return(View(db.userAccount.ToList()));
     }
 }
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new UserDBContext(
                       serviceProvider.GetRequiredService <DbContextOptions <UserDBContext> >()))
            {
                // Look for any board games.
                if (context.Logins.Any())
                {
                    return;   // Data was already seeded
                }

                context.Logins.AddRange(
                    new Models.Login
                {
                    Email    = "*****@*****.**",
                    Password = "******"
                },
                    new Models.Login
                {
                    Email    = "*****@*****.**",
                    Password = "******"
                },
                    new Models.Login
                {
                    Email    = "*****@*****.**",
                    Password = "******"
                });;

                context.SaveChanges();
            }
        }
        public AuthResult Auth(AuthRuest AuthQ)
        {
            if (AuthQ == null || string.IsNullOrEmpty(AuthQ.Account))
            {
                throw new AngleX.CustomException("用户名不应为空");
            }
            if (string.IsNullOrEmpty(AuthQ.Evidence))
            {
                throw new AngleX.CustomException("输入密码不应为空");
            }
            string md5Code = AngleX.EncodingHelper.ToMD5(AuthQ.Evidence);

            AuthResult authR = new AuthResult();

            using (UserDBContext db = new UserDBContext()) {
                authR.UserID = db.AuthAccount.Where(T => T.Account == AuthQ.Account)
                               .Where(T => T.PwdMD5 == md5Code)
                               .Select(T => T.ID)
                               .FirstOrDefault();
            }
            if (string.IsNullOrEmpty(authR.UserID))
            {
                authR.Code     = 1;
                authR.ErrorMsg = "账户密码错误";
            }
            return(authR);
        }
Exemple #25
0
        public ActionResult Delete(int id)
        {
            if (!IsUserLoggedIn() || !IsUserAdmin())
            {
                TempData["RedirectMessage"] = "Access denied. Please login.";
                return(RedirectToAction("Index", "Home"));
            }

            if (Int32.Parse(Session["UserID"].ToString()) == id)
            {
                return(RedirectToAction("Index", new { result = 0, delete = 1 }));
            }

            using (UserDBContext db = new UserDBContext())
            {
                bool success;

                if (id <= 0)
                {
                    return(RedirectToAction("Index", new { result = 0, delete = 1 }));
                }

                success = db.DeleteUser(id);
                return(RedirectToAction("Index", new { result = success ? 1 : 0, delete = 1 }));
            }
        }
Exemple #26
0
 private void DeleteButton_Click(object sender, RoutedEventArgs e)
 {
     if ((imageName != "" || imgByteArrDB != null) && IsValidEmail(EmailAddress.Text.ToString()))
     {
         foreach (UserDBContext user in users)
         {
             if (user.Email.Equals(EmailAddress.Text.ToString()))
             {
                 UserDBContext.IntitalizeDB();
                 UserDBContext.Delete(EmailAddress.Text.ToString());
                 InitializeDataGrid();
                 ClearAll();
                 WindowSuccess success = new WindowSuccess();
                 success.SetContent("Account Deleted Succefully");
                 success.Show();
             }
         }
     }
     else
     {
         WindowError error = new WindowError();
         error.SetContent("Account Is Not Selected");
         error.Show();
     }
 }
        public ActionResult ForgotPassword(string EmailID)
        {
            // Verify Email
            // Generate Reset Password Link
            // Send Email

            string message = "";
            bool   status  = false;

            using (UserDBContext db = new UserDBContext())
            {
                var account = db.Users.Where(x => x.EmailID == EmailID).FirstOrDefault();
                if (account != null)
                {
                    // send email for reset password
                    string resetCode = Guid.NewGuid().ToString();
                    SendVerificationLinkEmail(account.EmailID, resetCode, "ResetPassword");
                    account.ResetPasswordCode = resetCode;

                    db.Configuration.ValidateOnSaveEnabled = false;
                    db.SaveChanges();
                    message = "Reset password link has been sent to your email id.";
                }
                else
                {
                    message = "Account not found";
                }
            }
            ViewBag.Message = message;
            return(View());
        }
Exemple #28
0
 public static List <User> GetAllUser()
 {
     using (UserDBContext db = new UserDBContext())
     {
         return(db.User.ToList());
     }
 }
        public ActionResult ResetPassword(ResetPasswordModel model)
        {
            string message = "";

            if (ModelState.IsValid)
            {
                using (UserDBContext db = new UserDBContext())
                {
                    var user = db.Users.Where(x => x.ResetPasswordCode == model.ResetCode).FirstOrDefault();
                    if (user != null)
                    {
                        user.Password          = Crypto.Hash(model.NewPassword);
                        user.ResetPasswordCode = "";
                        db.Configuration.ValidateOnSaveEnabled = false;
                        db.SaveChanges();
                        message = "New Password Updated Successfully";
                    }
                }
            }
            else
            {
                message = "Something Invalied";
            }

            ViewBag.Message = message;
            return(View(model));
        }
        public MainWindowViewModel()
        {
            dbConnection    = new DBConnection();
            productRepo     = new ProductRepository();
            transactionRepo = new TransactionRepository();
            userRepo        = new UserRepository();

            userDBContext        = new UserDBContext(userRepo, dbConnection);
            productDBContext     = new ProductDBContext(productRepo, dbConnection);
            transactionDBContext = new TransactionDBContext(transactionRepo, dbConnection);

            Auth.CreateInstance(userRepo);
            startingView           = new StartingViewModel();
            loginView              = new LoginViewModel();
            dashboardView          = new DashboardViewModel();
            profileView            = new UserProfileViewModel();
            listProdukView         = new ListProductViewModel(productRepo);
            createProductView      = new CreateProductViewModel(productRepo);
            createTransactionView  = new CreateTransactionViewModel(transactionRepo, productRepo);
            editProductView        = new EditProductViewModel();
            transactionHistoryView = new TransactionHistoryViewModel();
            registerView           = new RegisterViewModel(userRepo);
            salesRecapView         = new SalesRecapViewModel();
            Mediator.Subscribe("Change View To Start", GoToStart);
            Mediator.Subscribe("Change View To Dashboard", GoToDasboard);
            Mediator.Subscribe("Change View To Profile", GoToProfile);
            Mediator.Subscribe("Change View To Product List", GoToProductList);
            Mediator.Subscribe("Change View To Create Product", GoToCreateProduct);
            Mediator.Subscribe("Change View To Create Transaction", GoToCreateTransaction);
            Mediator.Subscribe("Change View To Edit Product", GoToEditProduct);
            Mediator.Subscribe("Change View To Transaction History", GoToTransactionHistory);
            Mediator.Subscribe("Change View To Sales Recap", GoToSalesRecap);
            CurrentView = startingView;
        }
Exemple #31
0
 public UserRepository(UserDBContext context)
 {
     this.DBcontext = context;
 }