Example #1
0
        //public async Task<IActionResult> Create([Bind("Id,UserId,Nic,Address,Dob,BloodGroup,EmergencyContactName,EmergencyContactPhone,EmergencyContactAddress,Notes")] Patients patients, [Bind("Id,Name,Email,Password,ClinicId")] Users users)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        _context.Add(patients);
        //        await _context.SaveChangesAsync();
        //        return RedirectToAction(nameof(Index));
        //    }
        //    ViewData["UserId"] = new SelectList(_context.Users, "Id", "Email", patients.UserId);
        //    return View(patients);
        //}

        public async Task <IActionResult> Create(PatientUser patientUser)
        {
            Patients patient = new Patients();

            if (ModelState.IsValid)
            {
                Users user = new Users();
                user.Name     = patientUser.Name;
                user.Email    = patientUser.Email;
                user.Password = Hashing.CalculateMD5Hash(patientUser.Password);

                _context.Add(user);
                await _context.SaveChangesAsync();

                patient.UserId  = user.Id;
                patient.Address = patientUser.Address;
                patient.Dob     = patientUser.Dob;
                patient.Nic     = patientUser.Nic;

                _context.Add(patient);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["UserId"] = new SelectList(_context.Users, "Id", "Email", patient.UserId);
            return(View(patient));
        }
        public async Task <IActionResult> Create(DoctorUser doctorUser)
        {
            Doctors doctors = new Doctors();

            if (ModelState.IsValid)
            {
                Users user = new Users();
                user.Name     = doctorUser.Name;
                user.Email    = doctorUser.Email;
                user.Password = Hashing.CalculateMD5Hash(doctorUser.Password);

                _context.Add(user);
                await _context.SaveChangesAsync();

                doctors.UserId             = user.Id;
                doctors.Specialization     = doctorUser.Specialization;
                doctors.RegistrationNumber = doctorUser.RegistrationNumber;
                doctors.Phone = doctorUser.Phone;

                _context.Add(doctors);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["UserId"] = new SelectList(_context.Users, "Id", "Email", doctors.UserId);
            return(View(doctors));
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,Name,Email,Password,ClinicId")] Users users)
        {
            if (id != users.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    users.Password = Hashing.CalculateMD5Hash(users.Password);
                    _context.Update(users);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UsersExists(users.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ClinicId"] = new SelectList(_context.Clinics, "Id", "Address", users.ClinicId);
            return(View(users));
        }
        public async Task <IActionResult> PostUsers([FromBody] Users users)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            users.Password = Hashing.CalculateMD5Hash(users.Password);

            _context.Users.Add(users);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetUsers", new { id = users.Id }, users));
        }
        public async Task <IActionResult> PutUsers([FromRoute] int id, [FromBody] Users users)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.Entry(users).State = EntityState.Modified;

            if (id != users.Id)
            {
                return(BadRequest());
            }

            string currentPassword = _context.Users.Find(id).Password;

            if (users.Password == null)
            {
                users.Password = currentPassword;
            }


            users.Password = Hashing.CalculateMD5Hash(users.Password);

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UsersExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public async Task <IActionResult> Create([Bind("Id,Name,Email,Password,ClinicId")] Users users)
        {
            users.Password = Hashing.CalculateMD5Hash(users.Password);
            if (ModelState.IsValid)
            {
                var curUser = _context.Users.SingleOrDefault(u => u.Email == users.Email);
                if (curUser != null)
                {
                    return(Ok("Email already exist" +
                              ""));
                }

                _context.Add(users);
                await _context.SaveChangesAsync();

                await this.SendEmailAsync(users.Email, "Successfully Registered", "Hi! This is to inform you that your registration was successfull at Medecs");

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ClinicId"] = new SelectList(_context.Clinics, "Id", "Address", users.ClinicId);
            return(View(users));
        }
        public ActionResult MobileLogin(string email, string password)
        {
            if (email == null || password == null)
            {
                return(Ok("Invalid Request"));
            }

            //Users userParam = request;
            string pass = Hashing.CalculateMD5Hash(password);



            var user = _context.Users
                       .Include(u => u.Patients)
                       .Include("Patients.Appointments.Prescriptions")
                       .Include(u => u.Inventories)
                       .Include(u => u.UserRoleGroups)
                       .ThenInclude(rg => rg.RoleGroup)
                       .ThenInclude(rco => rco.RoleCarryOuts)
                       .ThenInclude(r => r.Role)
                       .SingleOrDefault(u => u.Email == email &&
                                        u.Password == pass);

            //var appointments = _context.Appointments.Include(a => a.Clinic)
            //            .Include(a => a.CreatedByNavigation).Include(a => a.Doctor)
            //            .Include(a => a.Patient).Include(a => a.Session)
            //            .Where(a => a.Patient.UserId == user.Id );

            //user.Appointments = appointments;


            if (user == null)
            {
                return(Ok("Invalid Credentials, User Not Found"));
                //return Forbid("Invalid Credentials");
            }

            //List<string> roles = new List<string>();

            //foreach(UserRoleGroups urg in user.UserRoleGroups)
            //{
            //    RoleGroups rg = urg.RoleGroup;

            //    foreach(RoleCarryOuts rco in rg.RoleCarryOuts)
            //    {
            //        roles.Add(rco.Role.Description);
            //    }
            //}

            //string role = user.UserRoleGroups.SingleOrDefault().RoleGroup.RoleCarryOuts.SingleOrDefault().Role.Description;

            //security key
            string securityKey = _appSettings.JwtKey;
            //symmetric security key
            var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));

            //signing credentials
            var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature);

            bool isManager    = false;
            bool isDoctor     = false;
            bool isAdmin      = false;
            bool isPatient    = false;
            bool isAccountant = false;

            //add claims
            var claims = new List <Claim>();

            //claims.Add(new Claim(ClaimTypes.Role, "Administrator"));
            //claims.Add(new Claim(ClaimTypes.Role, "Reader"));
            //claims.Add(new Claim("RoleGroup", role));
            claims.Add(new Claim(ClaimTypes.Name, user.Name));
            claims.Add(new Claim(ClaimTypes.Email, user.Email));

            HttpContext.Session.SetString("Name", user.Name);
            HttpContext.Session.SetString("Email", user.Email);

            foreach (UserRoleGroups urg in user.UserRoleGroups)
            {
                RoleGroups rg = urg.RoleGroup;

                if (rg.Name == "managers")
                {
                    HttpContext.Session.SetString("isManager", "1");
                    isManager = true;
                }
                if (rg.Name == "accountants")
                {
                    HttpContext.Session.SetString("isAccountant", "1");
                    isAccountant = true;
                }

                if (rg.Name == "patients")
                {
                    HttpContext.Session.SetString("isPatient", "1");
                    isPatient = true;
                }

                if (rg.Name == "doctors")
                {
                    HttpContext.Session.SetString("isDoctor", "1");
                    isDoctor = true;
                }

                if (rg.Name == "admins")
                {
                    HttpContext.Session.SetString("isAdmin", "1");
                    isAdmin = true;
                }

                claims.Add(new Claim("RoleGroup", rg.Name));

                foreach (RoleCarryOuts rco in rg.RoleCarryOuts)
                {
                    claims.Add(new Claim(ClaimTypes.Role, rco.Role.Description));
                }
            }

            claims.Add(new Claim("Id", user.Id.ToString()));


            //create token
            var token = new JwtSecurityToken(
                issuer: "mutants",
                audience: "users",
                expires: DateTime.Now.AddHours(1),
                signingCredentials: signingCredentials
                , claims: claims
                );

            user.Password = null;
            user.Token    = new JwtSecurityTokenHandler().WriteToken(token);

            HttpContext.Session.SetString("user_id", user.Id.ToString());
            HttpContext.Session.SetObject("user", user);

            //return token
            return(Ok(user));
        }
        public ActionResult Login(Users userParam)
        {
            string pass = Hashing.CalculateMD5Hash(userParam.Password);
            var    user = _context.Users
                          .Include(u => u.Appointments)
                          .Include(u => u.UserRoleGroups)
                          .ThenInclude(rg => rg.RoleGroup)
                          .ThenInclude(rco => rco.RoleCarryOuts)
                          .ThenInclude(r => r.Role)
                          .SingleOrDefault(u => u.Email == userParam.Email &&
                                           u.Password == pass);


            if (user == null)
            {
                return(Ok("Invalid Credentials"));
                //return Forbid("Invalid Credentials");
            }

            //List<string> roles = new List<string>();

            //foreach(UserRoleGroups urg in user.UserRoleGroups)
            //{
            //    RoleGroups rg = urg.RoleGroup;

            //    foreach(RoleCarryOuts rco in rg.RoleCarryOuts)
            //    {
            //        roles.Add(rco.Role.Description);
            //    }
            //}

            //string role = user.UserRoleGroups.SingleOrDefault().RoleGroup.RoleCarryOuts.SingleOrDefault().Role.Description;

            //security key
            string securityKey = _appSettings.JwtKey;
            //symmetric security key
            var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));

            //signing credentials
            var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature);

            //add claims
            var claims = new List <Claim>();

            //claims.Add(new Claim(ClaimTypes.Role, "Administrator"));
            //claims.Add(new Claim(ClaimTypes.Role, "Reader"));
            //claims.Add(new Claim("RoleGroup", role));
            claims.Add(new Claim(ClaimTypes.Name, user.Name));
            claims.Add(new Claim(ClaimTypes.Email, user.Email));

            foreach (UserRoleGroups urg in user.UserRoleGroups)
            {
                RoleGroups rg = urg.RoleGroup;

                claims.Add(new Claim("RoleGroup", rg.Name));

                foreach (RoleCarryOuts rco in rg.RoleCarryOuts)
                {
                    claims.Add(new Claim(ClaimTypes.Role, rco.Role.Description));
                }
            }

            claims.Add(new Claim("Id", user.Id.ToString()));


            //create token
            var token = new JwtSecurityToken(
                issuer: "mutants",
                audience: "users",
                expires: DateTime.Now.AddHours(1),
                signingCredentials: signingCredentials
                , claims: claims
                );

            user.Password = null;
            user.Token    = new JwtSecurityTokenHandler().WriteToken(token);

            HttpContext.Session.SetString("user_id", user.Id.ToString());
            HttpContext.Session.SetObject("user", user);

            //return token
            return(Ok(user));
        }