public static AuthenticationProperties CreateProperties(string userId)
        {
            var user = new UsersBuilder(new ApplicationRepository(new ApplicationDbContext())).GetUser(userId);

            IDictionary <string, string> data = new Dictionary <string, string>
            {
                { "user", JsonConvert.SerializeObject(user) }
            };

            return(new AuthenticationProperties(data));
        }
Exemple #2
0
 public ObjResponse InsertLog(ObjLogModel objLog)
 {
     try
     {
         return(new TRN_Logs().InsertLog(UsersBuilder.LogToEntity(objLog)));
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Exemple #3
0
 public List <ObjLogModel> GetListLogs()
 {
     try
     {
         return(UsersBuilder.ListLogToEntity(new TRN_Logs().GetListLogs()));
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Exemple #4
0
 public List <ObjLogModel> GetListLogs(DateTime startDate, DateTime endDate, int Uid)
 {
     try
     {
         return(UsersBuilder.ListLogToEntity(new TRN_Logs().GetListLogs(startDate.ToString("yyyy/MM/dd"), endDate.ToString("yyyy/MM/dd"), Uid)));
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new ApplicationUser()
            {
                UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, IsActive = true
            };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            var tokenExpiration = TimeSpan.FromDays(14); //same as local accounts;
            var identity        = await user.GenerateUserIdentityAsync(_repo.UserManager, "JWT");

            var props = new AuthenticationProperties()
            {
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
            };

            var ticket      = new AuthenticationTicket(identity, props);
            var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

            Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext context =
                new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                    Request.GetOwinContext(),
                    Startup.OAuthOptions.AccessTokenFormat, ticket);

            await new RefreshTokenProvider().CreateAsync(context);

            var pocoUser = new UsersBuilder(_repo).GetUser(user.Id);

            var tokenResponse = new
            {
                access_token  = accessToken,
                refresh_token = context.Token,
                token_type    = "bearer",
                expires_in    = tokenExpiration.TotalSeconds.ToString(),
                user          = JsonConvert.SerializeObject(pocoUser),
            };

            return(Ok(tokenResponse));
        }
Exemple #6
0
        public List <Entities.UsuarioModel> getUsers()
        {
            List <Entities.UsuarioModel> listUsers = new List <Entities.UsuarioModel>();

            try
            {
                listUsers = UsersBuilder.ListEntityToUser(usuarios.getUsers());
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message.ToString());
            }
            return(listUsers);
        }
Exemple #7
0
 public Entities.UsuarioModel RegisterUser(Entities.UsuarioModel pUsuario)
 {
     try
     {
         pUsuario.PasswordHash = Crypto.HashPassword(pUsuario.PasswordHash);
         int IdUser = usuarios.RegisterUser(UsersBuilder.UserToEntity(pUsuario));
         //Busco usuario con el ID registrado
         objuser = UsersBuilder.EntityToUser(usuarios.GetUserById(IdUser));
     }
     catch (Exception ex)
     {
         throw new ArgumentException(ex.Message.ToString());
     }
     return(objuser);
 }
Exemple #8
0
 public ResponseUser GetUserLogin(string User, string Password)
 {
     try
     {
         //Busco el Usuario con el fin de comparar SI es valido o NO
         objuser = UsersBuilder.EntityToUser(usuarios.GetUserByUser(User));
         if (objuser.UserName != null)
         {
             if (Crypto.VerifyHashedPassword(objuser.PasswordHash, Password))
             {
                 ResponseUser objres = new ResponseUser();
                 objres.User     = objuser;
                 objres.Response = true;
                 objres.Message  = "Consultado con Exito";
                 return(objres);
             }
             else
             {
                 ResponseUser objres = new ResponseUser();
                 objres.User     = objuser;
                 objres.Response = false;
                 objres.Message  = "La contraseña no corresponde.";
                 return(objres);
             }
         }
         else
         {
             ResponseUser objres = new ResponseUser();
             objres.User     = objuser;
             objres.Response = false;
             objres.Message  = "No se encontro informacion del usuario.";
             return(objres);
         }
     }
     catch (Exception ex)
     {
         throw new ArgumentException(ex.Message.ToString());
     }
 }
Exemple #9
0
        protected override void Seed(ClinicalStudyContext context)
        {
            var clinicCreator = new ClinicsBuilder();
            var clinics       = clinicCreator.GetClinics();


            UsersBuilder usersBuilder = new UsersBuilder();
            var          users        = usersBuilder.GetDemoUsers(clinics.FirstOrDefault());
            var          moreUsers    = usersBuilder.GetRandomDemoUsers(clinics);

            users = users.Concat(moreUsers).ToList();
            foreach (var user in users)
            {
                context.Users.Add(user);
            }
            var doctor = users.FirstOrDefault(u => u.Role == ClinicalStudyRoles.Doctor);


            //as any other entities are binded to Clinic, we do not need to add them explicitely
            //EF itself will take care about it
            foreach (var clinic in clinics)
            {
                context.Clinics.Add(clinic);
            }

            base.Seed(context);
            context.SaveChanges();

            IClinicalStudyContextFactory factory = new SingleContextFactory(context);
            PatientsBuilder patientsBuilder      = new PatientsBuilder(
                new DemographicFormDataRepository(factory),
                new VitalsFormDataRepository(factory),
                new AdverseEventFormDataRepository(factory),
                new ElectrocardiogramFormDataRepository(factory),
                new HappinessFormDataRepository(factory),
                new InventoryFormDataRepository(factory),
                new AttachmentRepository(factory),
                clinicalStudyDesign);



            List <DoctorWithRequiredPatients> doctorsToGeneratePatients = new List <DoctorWithRequiredPatients>();

            foreach (var user in users.Where(u => u.Role == ClinicalStudyRoles.Doctor))
            {
                doctorsToGeneratePatients.Add(new DoctorWithRequiredPatients()
                {
                    Doctor         = user,
                    PatientsNumber = user == doctor ? 6 : PeopleDataProvider.GetPatientForDoctorNumber()
                });
            }

            bool firstPatient       = true;
            int  firstPatientNumber = 25;

            for (int i = 0; i < doctorsToGeneratePatients.Max(d => d.PatientsNumber); i++)
            {
                foreach (var doctorWithRequiredPatient in doctorsToGeneratePatients)
                {
                    if (i < doctorWithRequiredPatient.PatientsNumber)
                    {
                        var patient = clinicalStudyDesign.CreatePatient(doctorWithRequiredPatient.Doctor);
                        if (firstPatient)
                        {
                            patient.PatientNumber = firstPatientNumber;
                            patient.Caption       = "Subj A0" + firstPatientNumber.ToString();
                            firstPatient          = false;
                        }
                        context.SaveChanges();
                        var demoPatientState = PeopleDataProvider.GetNewDemoPatientState();
                        patientsBuilder.PopulatePatientInfoAndDemographics(patient, demoPatientState);
                    }
                }
            }

            context.SaveChanges();

            QueriesBuilder builder = new QueriesBuilder {
                Patients = context.Patients.ToList(),
                AdverseEventFormDatas      = context.AdverseEventFormDatas.ToList(),
                DemographicFormDatas       = context.DemographicFormDatas.ToList(),
                ElectrocardiogramFormDatas = context.ElectrocardiogramFormDatas.ToList(),
                HappinessFormDatas         = context.HappinessFormDatas.ToList(),
                InventoryFormDatas         = context.InventoryFormDatas.ToList(),
                VitalsFormDatas            = context.VitalsFormDatas.ToList()
            };
            var queries = builder.BuildQueries(users.Single(u => u.Id == 2), users.Single(u => u.Id == 1));

            foreach (var query in queries)
            {
                context.Queries.Add(query);
            }
            context.SaveChanges();


            context.Timepoints.Add(
                new Timepoint()
            {
                DateAndTime = DateTime.Now, WasCorrectedAfterCreation = false
            });
            context.SaveChanges();
        }
        public async Task <IHttpActionResult> RegisterFacebook(string facebookToken)
        {
            if (String.IsNullOrEmpty(facebookToken))
            {
                return(BadRequest("Facebook Token Cannot be empty"));
            }
            var facebookId = "";
            var email      = "";
            var first      = "";
            var last       = "";

            try
            {
                var client = new FacebookClient(facebookToken);
                var result = client.Get("/me?fields=id,first_name, last_name,email");
                var me     = JsonConvert.DeserializeObject <JObject>(result.ToString());
                facebookId = me["id"].ToString();

                email = me["email"]?.ToString();
                if (string.IsNullOrEmpty(email))
                {
                    return(BadRequest("FanWord does not have access to your Facebook email. Please go into your Facebook settings and allow FanWord to access your email to continue"));
                }
                first = me["first_name"].ToString();
                last  = me["last_name"].ToString();
            }
            catch (FacebookOAuthException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (Exception ex)
            {
                return(BadRequest("Error " + ex.Message));
            }

            // Get user by facebook id
            var existing = UserManager.Users.FirstOrDefault(m => m.Logins.Any(j => j.ProviderKey == facebookId));

            if (existing == null)
            {
                // User not found by facebook id
                // Try e-mail (the user may already exist via regular login)
                existing = UserManager.Users.Include(m => m.ContentSource).FirstOrDefault(m => m.Email == email);

                if (existing == null)
                {
                    existing                = new ApplicationUser();
                    existing.Email          = email;
                    existing.UserName       = email;
                    existing.DateCreatedUtc = DateTime.UtcNow;
                    existing.FirstName      = first;
                    existing.LastName       = last;
                    existing.IsActive       = true;
                    var result = await UserManager.CreateAsync(existing);

                    if (!result.Succeeded)
                    {
                        return(GetErrorResult(result));
                    }
                    try
                    {
                        await UserManager.AddLoginAsync(existing.Id, new UserLoginInfo("Facebook", facebookId));

                        await UserManager.AddClaimAsync(existing.Id, new Claim("FacebookAccessToken", facebookToken));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        throw;
                    }
                }
                else
                {
                    return(BadRequest("An account with your Facebook e-mail address already exists. Please login using your e-mail and password instead."));
                }
            }

            var tokenExpiration = TimeSpan.FromDays(14); //same as local accounts;

            var identity = await existing.GenerateUserIdentityAsync(_repo.UserManager, "JWT");

            var props = new AuthenticationProperties()
            {
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
            };

            var ticket      = new AuthenticationTicket(identity, props);
            var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

            Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext context =
                new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                    Request.GetOwinContext(),
                    Startup.OAuthOptions.AccessTokenFormat, ticket);

            await new RefreshTokenProvider().CreateAsync(context);

            var user          = new UsersBuilder(_repo).GetUser(existing.Id);
            var tokenResponse = new
            {
                access_token  = accessToken,
                refresh_token = context.Token,
                token_type    = "bearer",
                expires_in    = tokenExpiration.TotalSeconds.ToString(),
                user          = JsonConvert.SerializeObject(user),
            };

            return(Ok(tokenResponse));
        }